B
B
bzotsss2021-09-13 09:14:28
React
bzotsss, 2021-09-13 09:14:28

Why is the value not coming to useState?

I have a custom hook useApiData
here is its code :

import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { getPageCountAC } from "../redux/mainPageReducer";
import { getUsersAC } from "../redux/mainPageReducer";

export const useApiData = () => {
  const dispatch = useDispatch()
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
  const [results,setResults] = useState([])

  useEffect(() => {
    const getApiData = async () => {
      try {
        setIsLoading(true);
        const response = await fetch("https://itrex-react-lab-files.s3.eu-central-1.amazonaws.com/react-test-api.json");
        const results = await response.json();
        if (response.status!==200) {
          throw new Error('Error');
        }
        setData(results);
        setResults(results)
        dispatch(getUsersAC(results))
        dispatch(getPageCountAC(results.length))
      } catch (e) {
        setIsLoading(false);
        setIsError(false);
      } finally {
        setIsLoading(false);
      }
    };
    getApiData();
  }, []);
  return {
    data,
    isLoading,
    isError,
    setData,
    results
  };
};

I get data from it via useApiDatathis way:
const users = useApiData();
  const [userss, setUserss] = useState(users.data);

There is a value in usersbut at the same time it does not set useStatein what could be the problem? How to fix? Or rather, what am I not understanding and doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-13
@Alexandroppolus

Everything is the same as here https://qna.habr.com/q/1041970
specifically in this case const [userss, setUserss] = useState(users.data); looks like redundant, because you can use the same users. setData, that is, the state is already there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question