Home > Software engineering >  React native useState doesn't rerender
React native useState doesn't rerender

Time:06-15

I was following Mosh's react native course when I ran into this problem after trying to delete item from a flatlist using the useState hook it doesn't rerender is there any thing wrong in this code or this is some sort of bug I have I would really appreciate the help this is my code and I'm using handleDelete as an onPress event:

const [messages, setMessages] = useState(initialMessages);

const handleDelete = (message) => {
    setMessages(messages.filter(m => m.id != message.id));
}

CodePudding user response:

if it does not re-render your code then you can create your own re-render hook which you can invoke whenever you wanna re-render your screen

  1. add this out of your functional component scope or you can also add it inside your functional component but it is better to do it outside.
    const useForceUpdate = () => {
      const [, forceUpdate] = useReducer((i) => i   1, 0);
      return forceUpdate;
    };
  1. then create the object of your hook like this
    const forceUpdate = useForceUpdate();
  1. then you can call forceUpdate(); function which will re-render your screen

In Your case, you can call it after setMessages

const [messages, setMessages] = useState(initialMessages);

const handleDelete = (message) => {
    setMessages(messages.filter(m => m.id != message.id));
    forceUpdate()
}

CodePudding user response:

const [messages, setMessages] = useState(initialMessages);

const handleDelete = (message) => {
    setMessages(messages.filter(m => m.id != message.id));
}

useEffect(()=>{
handleDelete();
},[messages])
  • Related