0

I have a function that sends two requests to the server when called, but only needs one.

function Welcome() { var styles = { backgroundColor: "#eee" }; const [isLoaded, setIsLoaded] = useState(false); const [cats, setCats] = useState([]); if(!isLoaded) { setIsLoaded(true); fetch('http://localhost:3001/api/categoryList') .then((response) => response.json()) .then((response) => { setCats(response); }); } return ( <div style={{textAlgin:"center"}} className="Welcome"> <title>{gloArray.titleProject}</title> <div id="546" className="prevTypePlace" > { cats.map((value) => <Typepreview image={value.workImage} id={value.workId} key={value.workId} name={value.workName} />) } </div> </div> ); } 

I suspect that the component is drawn twice, but I don't know how to fix it

1 Answer 1

2

useEffect is used when you need some side effect, so put this condition inside one:

useEffect(() => { if(!isLoaded) { setIsLoaded(true); fetch('http://localhost:3001/api/categoryList') .then((response) => response.json()) .then((response) => { setCats(response); }); } }, [isLoaded]) 

currenty, this if condition is being called on every render, but we don't want that, we want it to be called, only when isLoaded changes

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.