Home > OS >  How use react suspense with redux toolkit?
How use react suspense with redux toolkit?

Time:12-20

I am use Redux toolkit for show data of a API and i need show for the user a "loading data..." or a spinner before of show the city information.

I am trying use the React Suspense, but, dont work. Probably i am doing thing wrong.

informationCIty.js (Code with Suspense)

import React, { useEffect, Suspense } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getInformationCity } from "../informationCity/informationCitySlice";

export const InformationCity = () => {
  const dispatch = useDispatch();
  const selectedCity = useSelector((state) => state?.cities?.selectedCity);
  const informacoes = useSelector(
    (state) => state?.informationCity?.dataInformation
  );

  useEffect(() => {
    dispatch(getInformationCity(selectedCity));
  }, [dispatch, selectedCity]);

  return (
    <div>
      <Suspense fallback="Loading information of city">
        {informacoes.map((item, i) => (
          <li key={i}>
            City ID: {item.id}
            <br />
            City Name: {item.nome}
            <br />
          </li>
        ))}
      </Suspense>
    </div>
  );
};

Code full in codesandbox

Someone help me please??

CodePudding user response:

According to the posted sandbox, it seems that loading status has already been managed by createAsyncThunk, and the same pattern is used across the app.

Perhaps unless Suspense is mandatory, this component could easily implement loading status by reading it from the state: (forked example with the following changes: codesandbox)

const loading = useSelector((state) => state?.informationCity?.loading);

  return (
    <div>
      {informacoes && informacoes.length > 0 && loading && (
        <h2>"Loading information of city"</h2>
      )}
      {informacoes &&
        informacoes.length > 0 &&
        !loading &&
        informacoes.map((item, i) => (
          <li key={i}>
            City ID: {item.id}
            <br />
            City Name: {item.nome}
            <br />
          </li>
        ))}
    </div>
  );

CodePudding user response:

Suspense for data fetching on the client is still not officially supported in React 18. From the release notes:

Ad hoc data fetching with Suspense is technically possible, but still not recommended as a general strategy.

Until React has an official story for this, Redux will also not have one. The risk that React changes their approach (which they have done multiple times in the past) is just too high.

  • Related