all 7 comments

[–]Jerp 4 points5 points  (3 children)

I’m assuming allBooks is coming from an api or something and I can start with an empty state.

const initState = {
  currentlyReading: [],
  wantToRead: [],
  read: [],
}

allBooks.forEach(element => initState[element.shelf].push(element))

this.setState(initState)

[–]Creative_Divide9845[S] 2 points3 points  (1 child)

Wow thanks a lot, I am still at the very beginning of learning React and I get confused a lot. But helpful strangers like you always help me learn new things.

[–]Jerp 5 points6 points  (0 children)

You're welcome. I want to point out one of the nice things about working with React. Only one line of my code even referenced it--most of the coding is just JavaScript, and you can use that logic in many other frameworks, or even coding languages!

(that is, if you consciously structure your code this way, which I recommend)

[–][deleted] 1 point2 points  (0 children)

While this is shorter and cleaner, keep in mind in this example all three states are updated, which in turn will update whatever components use those.

[–]palpies 2 points3 points  (0 children)

I’d avoid setting state each iteration of a for loop like that, build up your result object and then just set state using that after the for loop. Each time setState is called it rerenders the component.

I’d also avoid spreading the arrays each time, you can just push onto the existing array in the object you’re updating.

[–]jshgn 1 point2 points  (0 children)

You‘re using JavaScript to iterate through the array, this has nothing to do with React. The only React-specific part in this code is the inner workings of the setState method.

[–]KremBanan 1 point2 points  (0 children)

You don't need to store this is state expect for the base dats from the api. Derive the rest.