Home > Mobile >  How can I change the array key value before passing to the state in react?
How can I change the array key value before passing to the state in react?

Time:10-17

Question, I have this state coming from the backend It's a array of messages that will be store in state using useState. This state will be pass on in the child component. The problem is I want to change value of a specific key before storing it into the state.

Sample

Messages Array sample data

const messages = [
      {
        value: 'sample value one',
        status: false,
      },
      {
        value: 'sample value two',
        status: false,

      },
    ];

UseSelector

const messageGetById = useSelector((state) => state.messageGetById);
  const { message } = messageGetById;

UseEffect

useEffect(() => {
    if (message) {
      setCurrentMessage(message);
    }
  }, [message]);

The output that I want is before passing the message into setCurrentMessage, all the value of status will be change to true.

Thanks!

CodePudding user response:

You can use map method to map thought the array and change the status to true.

  useEffect(() => {
    if (message) { 
    const newMessages = messages?.map((mess) => {
        return {...mess, status: true}})
      setCurrentMessage(newMessages);
    }}, [message]);

CodePudding user response:

Set the mapped state with useEffect

useEffect(() => {
  const data = [...message];
  if (data.length > 0) {
    data.map((ele) => ({
      value: "YOUR CHANGED VALUE",
      status: ele.status,
    }));
    setCurrentMessage(data);
  }
}, [message]);

  • Related