Search code examples
javascriptreactjsreact-hooksreact-apollo

React TypeError: Cannot read property 'getDates' of undefined


today i decided to update the dependencies of my react project and my component Home didn't work anymore, i'm actually working with a apollo client and apollo react hooks, this is mi Home component file:

function Home(props) {
    const {
        loading,
        data: { getPosts: posts }
    } = useQuery(FETCH_POSTS_QUERY);

    return (
        <Grid columns={3} stackable={true} className={loading ? 'loading' : ''}>
            <Grid.Row className='page-title'>
                <h1>Recent Posts</h1>
            </Grid.Row>
            <Grid.Row>
                {user && (
                    <Grid.Column>
                        <PostForm user={user} />
                    </Grid.Column>
                )}
                {loading ? (
                    <Loading />
                ) : (
                    posts &&
                    posts.map(post=> (
                        <Grid.Column key={post._id} style={{ marginBottom: 20 }}>
                            <PostCard post={post} />
                        </Grid.Column>
                    ))
                )}
            </Grid.Row>
        </Grid>
    );
}

and i'm getting this error in the browser: "TypeError: Cannot read property 'getPosts' of undefined"

i'm trying to fix it with this little code variation:

function Home(props){
    let posts = '';
    const { user } = useContext(AuthContext);
    const { loading, data } = useQuery(FETCH_POSTS_QUERY);

    if (data) {
        posts = data.getPosts;
    }

And everything works fine, but if i add a new Post updating the apollo cache, that cache update correctly with old posts and new post, but the frontend didn't show it, only show old posts until i refresh the page manually.

Edit: This is the code from the PostForm component, i updated the Home component too adding the PostForm:

function PostForm(props) {
    const { values, handleChange, handleSubmit } = useForm(createPostCallback, {
        title: 'Example Title',
        body: ''
    });

    const [createPost] = useMutation(CREATE_POST_MUTATION, {
        variables: values,
        update(dataProxy, result) {
            const data = dataProxy.readQuery({
                query: FETCH_POSTS_QUERY
            });
            data.getPosts = [result.data.createPost, ...data.getPosts];
            dataProxy.writeQuery({
                query: FETCH_POSTS_QUERY,
                data
            });
            values.body = '';
        }
    });

    function createPostCallback() {
        createPost();
    }

Any idea how to fix the first code issue? Thanks in advance mates!


Solution

  • Queries for read and write cache in apollo works in a inmutable way. In order to do that, you have to use a new variable, you're using data to write the cache. Try doing this:

      const [createPost] = useMutation(CREATE_POST_MUTATION, {
        variables: values,
        update (proxy, result) {
          const data = proxy.readQuery({
            query: FETCH_POSTS_QUERY
          })
          const new_post = result.data.createPost //here's the new var
          proxy.writeQuery({
            query: FETCH_POSTS_QUERY,
            data: { getPosts: [new_post, ...data.getPosts] } // here you're using that var to write the cache
          })
          values.body = ''
        }
      })