Answer the question
In order to leave comments, you need to log in
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
};
};
useApiData
this way:const users = useApiData();
const [userss, setUserss] = useState(users.data);
users
but at the same time it does not set useState
in 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
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 questionAsk a Question
731 491 924 answers to any question