Home > Software design >  React native, state not defined in useSelector after fetch
React native, state not defined in useSelector after fetch

Time:03-18

I am trying to load data for my component in useEffect. How can I ensure the state is defined before I go to the next screen?

  const [rescueMeContent, setRescueMeContent] = useState({});

  useEffect(() => {
    async function fetchData() {
      const { payload } = await get('xxx');
      setRescueMeContent(payload);
    }
    fetchData();
  });

When I first run the app, on the next screen when I try and access the state like this I get an error saying its undefined:

  const {
    content: {
      splashScreen: {
        backgroundImage: { url },
        buttonText,
        informationText,
        title: pageTitle,
      },
    },
  } = useSelector((state) => state);

CodePudding user response:

useState works in inside only component. You can't reach that from other component. You must use react redux for to use useSelector. You must assign your fetch data to redux state with action. Then you can get that data with useSelector.

  • Related