0

there is such a production in react. I want the user to delete posts that they have shared. I do this:

  • When the user logs in, I keep the user id as a cookie.
  • I get the user name of the user that is equivalent to the id in the database with the captured id - HaoAsk
  • I check with the username of the user who shares the post with the username I received
  • if it is equal, I allow the user with setOwner.

But it goes into an endless loop.

const user = response.data.filter((dataItem) => (dataItem._id === userid));

const userNickname = JSON.stringify(user.map((value) => { return value.nickName }))
const nickName = userNickname.slice(2, -2)

const deneme1 = posts.filter( (data) => (data.who === nickName))

deneme1 ? setOwner([{ who: nickName,  status: true}]) : setOwner([{ status: false }])

console.log(owner)

When I use the following code, everything I write with console.log enters an infinite loop. I couldn't figure it out.

deneme1 ? setOwner ([{who: nickName, status: true}]): setOwner ([{status: false}])

Thanks in advance, Yours!

Berat Bozkurt
  • 111
  • 4
  • 13

1 Answers1

1

For any functional component, you normally want to make sure you don't use set outside the event function.

In your case,

   const onClick = e => { 
     // safe to use set method
     setOwner()
   }

   return (
      <Component onClick={onClick} user={user} />
   )

Because everything inside a functional component is inside the render cycle. It'll run when react try to refresh the display. In your case you set a state variable which triggers the render and then set the variable and then the infinite circle :)

What this means is that you have to find out an event after you initialize your component. In your case, it's a bit tricky, because you want to call this event right away automatically for you.

Please refer to something like this, How to call loading function with React useEffect only once

windmaomao
  • 7,120
  • 2
  • 32
  • 36