I know this is a common question, but after hours of searching for an answer, I decided to ask for help.
I'm trying to pass a state variable to a component, but the component was rendered before the value was set
my code:
import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import Seguradora from "../../components/seguradora/seguradora.component";
const CorretorasShow = () => {
const obj = useLocation();
const [names, setNames] = useState([]);
useEffect(() => {
const url =
"http://localhost:3001/corretoras/63338f415c502044e953d408"
obj.state._id;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setNames(json.seguradora); // <<<<<< setState
} catch (error) {
console.log("error", error);
}
};
fetchData();
}, []);
return (
<div>
<Seguradora props={names} /> //<<<<< state varible
</div>
);
};
I've tried useMemo, useRef and ternary operator to no avail. I'm not an expert programmer and I'm new to reactJS so I may have done something wrong with these workarounds
CodePudding user response:
You need to add names
to useEffect dependency array and call fetchData() only if names is empty array.
useEffect(() => {
const url =
"http://localhost:3001/corretoras/63338f415c502044e953d408"
obj.state._id;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setNames(json.seguradora);
} catch (error) {
console.log("error", error);
}
};
names.length === 0 && fetchData();
}, [names]);
CodePudding user response:
Since names
is an Array, you can check if the Array is populated to conditionally render your component, like this:
return (
<div>
{ names.length > 0 ? <Seguradora props={names} /> : null}
</div>
);