2

I am working on a react and apollo project and I have following situation.

@graphql(TodosQuery)
class Table extends Component {
  render(){
    return (
      <div>
        {this.props.data.todos.map(...)}
      </div>
    )
  }
}

const TodosQuery = gql`
  query TodosQuery {
    todos {
      id
      name
      deadline
    }
  }
`

My app allows to open modal for each todo with detailed information. And now I have question how can I get todo data from cache to display them in modal (another component). I know that all proper data are in apollo cache but i'm not sure how to get one todo from apollo.

@graphql(...)
class Modal extends Component {
  ...
}

Can I use somehow readFragment? or should I write another query similar to TodosQuery with id and fetchPolicy: "cache-only" eg.

const TodosQuery = gql`
  query TodosQuery($id: String!) {
    todos(id: $id) {
      id
      name
      deadline
    }
  }
`

Thanks for any idea.

magnat
  • 407
  • 4
  • 18

1 Answers1

0

I'm not sure how to do this with graphql cache but maby you can achieve this by storing the selected todo data in react state and pass it to the modal component as a prop.

class Table extends Component {
    consctructor(props) {
        super(props);
        this.state = { selectedTodo: {} }
    }

    render(){
        return (
            <div>
                {this.props.data.todos.map(...)}
            </div>
        );
    }
}

In your onClick function:

 this.setState({
    selectedTodo: this.props.data.todos.find(todo => todo.id === id)
 });

When rendering the Modal component:

<Modal todoData={this.state.selectedTodo} />
Zayco
  • 327
  • 4
  • 14