C Z
C Z

Reputation: 13

Question about building react state with fetch() and .then()

I have an issue when I tried to fetch a json file and build the react state.

import React, {
    Component
} from 'react';

class App extends Component {
    constructor() {
        super()
        this.state = {
            cards: []
        }
    }

    componentDidMount() {
        fetch('https://steamcdn-a.akamaihd.net/apps/583950/resource/card_set_1.3E50A21FB5DAFC5864FE5DE99E0EC84E4B3F00DB.json')
            .then(response => response.json())
            .then(cardsets => this.setState({
                cards: cardsets.card_set.card_list
            }))
    }

Above is the code I finished. It's working. So at this point I want to let my this.state.cards[i] object have a name 'color', and the value would be based on this.state.cards[i].is_blue or this.state.cards[i].is_red etc (these are just from the json file).

I'm wondering how could I do this. Please help me I'm very new to react.

Upvotes: 0

Views: 43

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44135

Just change your second then with a map:

.then(cardsets => this.setState({ cards: cardsets.card_set.card_list.map(card => card.color = card.is_red ? "red" : "blue")}));

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138457

You could map to the wanted format before setting it to the state:

this.setState({
 cards: cardsets.card_set.card_list.map(({ is_red, is_blue, ...rest }) => ({ 
   color: (is_red && "red") || (is_blue && "blue") || "black",
   ...rest
  })),
});

Then you can access cards[i].color while rendering.

Or you just extract the color directly when rendering:

 render() {
  const { cards } = this.state;

  return cards.map(card => {
   const { is_blue, is_red } = card;
   const color = (is_red && "red") || (is_blue && "blue") || "black";

   return <div style={{ color }} >Card</div>;
  });
}

Upvotes: 3

Related Questions