Sole
Sole

Reputation: 3340

SetState with data from React-query with React/Typescript

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} 

Upvotes: 0

Views: 3833

Answers (2)

Obaida Alhassan
Obaida Alhassan

Reputation: 601

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>
  );
}

Upvotes: 2

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

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>;
}

Upvotes: 1

Related Questions