Nababur's avatar
Level 43

React Query does not work in version 4

Hey Andre,

My code does not work in react-query version 4 , need help asap.

import { useQuery } from '@tanstack/react-query' export default function Reddit() { // const {data: posts, isLoading, errorMessage } = useFetch('https://www.reddit.com/r/aww.json');

const {
    data: posts,
    isLoading,
    isError,
    error,
    isSuccess,
} = useQuery('posts', fetchPosts);

function fetchPosts(){
    return fetch('https://www.reddit.com/r/aww.json').then(response => response.json());
}

return ( Reddit API {isLoading && Loading...} {isSuccess && ( {posts.data.children.map(post => ( <a href={https://reddit.com${post.data.permalink}}>{post.data.title}

            ))}
        </ul>
    )}

    {isError && <div>{error.message}</div>}
</div>

) }

0 likes
2 replies
LaryAI's avatar
Level 58

The code you provided seems to have some syntax errors and incorrect imports. Here's a corrected version of the code using react-query version 4:

import { useQuery } from 'react-query';

export default function Reddit() {
  const { data: posts, isLoading, isError, error, isSuccess } = useQuery('posts', fetchPosts);

  function fetchPosts() {
    return fetch('https://www.reddit.com/r/aww.json').then(response => response.json());
  }

  return (
    <div>
      <h1>Reddit API</h1>
      {isLoading && <p>Loading...</p>}
      {isSuccess && (
        <ul>
          {posts.data.children.map(post => (
            <li key={post.data.id}>
              <a href={`https://reddit.com${post.data.permalink}`} target="_blank" rel="noreferrer noopener nofollow">
                {post.data.title}
              </a>
            </li>
          ))}
        </ul>
      )}
      {isError && <div>{error.message}</div>}
    </div>
  );
}

Make sure you have installed the correct version of react-query (npm install react-query@4) and imported it correctly (import { useQuery } from 'react-query').

Nababur's avatar
Level 43

@LaryAI

Yes, i am using the latest version.

"dependencies": { "@tanstack/react-query": "^4.32.0", "@tanstack/react-query-devtools": "^4.32.0", "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "eslint-config-airbnb-base": "^15.0.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" },

Please or to participate in this conversation.