The question is published on by Tutorial Guruji team.
I have a function in react showPeople. This is the code:
const showPeople = () => { const people = workers.map((worker, i) => { return ( <div> <Worker id={worker.id} index={i} role={worker.role} /> </div> ) }) return people; }
Later in the component I want to call this function in order to show me some information for the workers. I call it like this:
<div> {showPeople()} </div>
And this is ok, but it is called only once. When I change the state it’s not called. So I have my updates only after I refresh the page. If i remove the parenthesis in the call, I get nothing on my screen. Does anyone knows what’s the problem? Sorry if this question is a duplicate, I am not sure I understood any of the previous answers connected tot his topic. Thanks
Answer
Edit your function to accept workers as parameter:
const showPeople = (workers) => { const people = workers.map((worker, i) => { return ( <div> <Worker id={worker.id} index={i} role={worker.role} /> </div> ) }) return people; }
And pass workers from state.
<div> {showPeople(this.state.workers)} </div>
It should re-render whenever your this.state.workers change and it will render with new workers.