Reputation: 109
useEffect does render the data from the axios get request. However in the console it logs the initial results as an empty array. const childRefs = useMemo(() => new Array(results.length).fill(0).map((i) => React.createRef()),[]);
This line requires the results state to return with the array from the axios request otherwise I get the error TypeError: Cannot read property 'current' of undefined
. If I pass the results state as an argument in useEffect then useEffect keeps calling without stoping. How do I get the results state set on the initial render without useEffect calling indefinitely?
export default function SwipePage() {
const [ results, setResults ] = useState([]);
const [ isOpen, setIsOpen ] = useState(false);
const { userState, setUserState } = useContext(UserContext);
const { id } = useParams();
const api = `http://localhost:5000/user/match/${id}`;
const alreadyRemoved = [];
useEffect(() => {
axios
.get(api, {
headers: {
Authorization: localStorage.getItem("jwt"),
"Content-Type": "application/json",
"Cache-Control": "no-cache",
},
})
.then((res) => {
setResults(res.data.user);
console.log(results, "Results")
});
}, []);
const childRefs = useMemo(() => new Array(results.length).fill(0).map((i) => React.createRef()),[]);
Upvotes: 0
Views: 415
Reputation: 403
With useMemo you will get a memoized result. Put the results into the dependency array of useMemo and your data will be recalculated if the results state was changed.
const childRefs = useMemo(() => new Array(results.length).fill(0).map((i) => React.createRef()),[results]);
Upvotes: 2