Function is not called when state is changed Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Function is not called when state is changed without wasting too much if your time.

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.

We are here to answer your question about Function is not called when state is changed - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji