1

How to force re-render when an array changes its value in ReactJS.

I have an array like

const [providers, setProviders] = useState<Array<any>>(props.filters?.providers!);

and when I call a delete function to remove one element of this array the view doesn't render.

let OnDelete = (prop: any, func: any, p: IFilter) => {
    const index = prop.findIndex((x: IFilter) => x.code == p.code);
    if (index !== -1) {
        prop.splice(index, 1);
    }
    func(prop);
};
2
  • 1
    Have you tried setProviders within the delete to see if that helps? Commented Feb 10, 2022 at 16:10
  • 1
    Just create a new array. It expects a new reference setProviders [...providers] /* or */ setProviders(Array.from(providers)) Commented Feb 10, 2022 at 18:48

1 Answer 1

2

I've a workaraund when I want the page to render againg when using hooks that works for me.

I Just declare a state and then change its value to force re-render, something like this

const [providers, setProviders] = useState<Array<any>>(props.filters?.providers!);
const [refresh, setRefresh] = useState<boolean>(false);

const OnDelete = (prop: any, func: any, p: IFilter) => {
    const index = prop.findIndex((x: IFilter) => x.code == p.code);
    if (index !== -1) {
        prop.splice(index, 1);
    }
    func(prop);
    setRefresh(!refresh) //**Here i force a re render when changing th state**
}

I hope it works for you :)

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

1 Comment

There's really no need for another hook call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.