Home > Blockchain >  How to toggle a boolean inside a nested object in react
How to toggle a boolean inside a nested object in react

Time:10-31

function App(){
    const Data = [
    {
          name:"CR7",
          Age:37,
          instagram:{
          id:1,
          followers:"493M",
          followed:true,
        }
  }
]
  Const [playersData,setData] =useState(Data)
  const Element = daplayersDatata.map(data=>{
        return (
              <button onClick={()=>toggleFollow()}>{data.instagram.followed ? "Followed" :"Unfollowed"}</button>
        )
    function toggleFollow(){
    "my question is how to toggle followed boolean ?"
    }
    return(
       <div>{Element}</div>
      )
    }

I've tried a lot of methods and nothing worked also I couldn't find something on the web. I hope someone will help me with this

CodePudding user response:

Your code is full of typos and programming mistakes. I have refactored the whole thing and wrote the toggle handler too so here is how it should have been:

const { useState } = require("react");

const Data = [
  {
    name: "CR7",
    Age: 37,
    instagram: {
      id: 1,
      followers: "493M",
      followed: true,
    },
  }
];

export default function App() {
  const [playersData, setPlayersData] = useState(Data);
  function toggleFollow(name) {
    setPlayersData((s) =>
      s.map((e) => {
        if (e.name !== name) return e;
        return {
          ...e,
          instagram: { ...e.instagram, followed: !e.instagram.followed },
        };
      })
    );
  }

  console.log({playersData})

  const Elements = playersData.map((data) => {
    return (
      <button key={data.name} onClick={() => toggleFollow(data.name)}>
        {data.instagram.followed ? "Followed" : "Unfollowed"}
      </button>
    );
  });

  return <div>{Elements}</div>;
}
  • Related