Home > Enterprise >  SetState with data from React-query with React/Typescript
SetState with data from React-query with React/Typescript

Time:10-20

I am trying to set the state using setState and it needs to default to the data from React-query, but on refresh it says undefined.

const fetchAlerts = async () => {
    const res = await fetch('https://jsonplaceholder.typicode.com/todos');
    return res.json();
};

 const { data, status } = useQuery('todos', fetchTodos, {
    staleTime: 5000,
});

const result = data;

const [fetchData, setFetchData] = React.useState<ITodo[]>(result);

then I map over the state object like:

{fetchData.map() etc} 

CodePudding user response:

Something like this should work. See codesandbox here for working example.

function Example() {
  const [fetchedData, setFetchedData] = React.useState([]);

  const fetchTodos = async () => {
    const res = await fetch("https://jsonplaceholder.typicode.com/todos");
    return res.json();
  };

  const { data: result } = useQuery("todos", fetchTodos, {
    staleTime: 5000
  });

  React.useEffect(() => {
    setFetchedData(result);
  }, [result]);

  return <p>{JSON.stringify(fetchedData)}</p>;
}

CodePudding user response:

I have set up a working example in the sandbox, you need to set the state data in useEffect and to wrap your app with QueryClientProvider to use userQuery successfully "just to mention that"

Sandbox link

// Alert component

import React, { useEffect } from "react";
import { useQuery } from "react-query";
import "./styles.css";

interface ITodo {
  userId: string;
  id: string;
  title: string;
}

const fetchAlerts = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos");
  return res.json();
};

export default function Component() {
  const [fetchData, setFetchData] = React.useState<ITodo[]>([]);

  const { data, status } = useQuery<ITodo[]>("mytodos", fetchAlerts, {
    staleTime: 5000
  });

  useEffect(() => {
    setFetchData(data ?? []);
  }, [data]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {fetchData.map((x) => (
        <li>
          {" "}
          {x.userId} - {x.id} - {x.title.substr(10)}
        </li>
      ))}
    </div>
  );
}

// App component

import "./styles.css";
import Component from "./component";
import { QueryClient, QueryClientProvider } from "react-query";
export default function App() {
  const queryClient = new QueryClient();
  return (
    <QueryClientProvider client={queryClient}>
      <div className="App">
        <Component />
      </div>
    </QueryClientProvider>
  );
}

  • Related