如何将状态值放入GraphQL缓存

时间:2018-07-16 01:58:57

标签: javascript reactjs graphql

每个待办事项在其末尾都有一个编辑按钮,当我单击完成时,单击的特定待办事项的编辑按钮会显示为灰色。现在,我担心的是,当我刷新页面时,它会将编辑按钮重新呈现为原始状态。如您所见,我在注释部分中尝试使用localStorage来存储状态值,并在刷新后仍然保留编辑按钮状态,但是,问题是当我单击任何其他待办事项以完成操作时,它将更改状态其他待办事项编辑按钮。我想知道是否有任何方法可以将编辑按钮状态存储在GraphQL Cache中,例如将完整状态存储在缓存中并持续存在的方式,还是有人可以在这里向我解释localStorage方法出了什么问题。谢谢!!

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      disabled: {
        id: ''
      },
      val: false //JSON.parse(localStorage.getItem('val'))

    }
    this.val = false;
  }

  updateTodo = async todo  => {

    await this.props.updateTodo({
      variables: {
        id: todo.id,
        complete: !todo.complete
      },
      update: store => {
        // Read the data from our cache for this query.
        const data = store.readQuery({ query: TodoQuery });
        const { val } = this.state;
        // Add our comment from the mutation to the end.
        data.todos = data.todos.map(x => x.id === todo.id ? {
          ...todo,
          complete: !todo.complete
        } : x);
        // Write our data back to the cache.
        store.writeQuery({ query: TodoQuery, data });
      }
    })

  };

    handleCheckBox = id => {
       let disabled = this.state.disabled;
       disabled[id] = !disabled[id];
       this.setState({ disabled });
       this.setState({val: this.state.disabled})
       // , () => {
       //   localStorage.setItem('val', JSON.stringify(this.state.val))
       // });
    }



  render() {
    const {data: {loading, todos}} = this.props;
    if(loading) {
      return null;
    }
    return (
       ...
        <div>
          {todos.map(todo => (
          <List key={todo.id}>
            <ListItem
              role={undefined}
              dense
              button
              onClick={() => this.updateTodo(todo)}
            ><Checkbox
                onClick={()=>this.handleCheckBox(todo.id)}
                checked={todo.complete}
             />
              <ListItemText primary={todo.text} />
              <ListItemSecondaryAction>
                <Button mini color="secondary" variant="fab" 
                      disabled={this.state.val[todo.id]}>
                 <Icon>edit_icon</Icon>
         </div>
    );
  }
}

export default compose(
  graphql(UpdateMutation, {name: "updateTodo"}),
  graphql(TodoQuery)
)(App);

0 个答案:

没有答案