0

I'm trying to make an app using API from https://swapi.co/
They have no pictures in their response so I thought to add them myself after fetching the data.

I'm fetching data from API in action like that

export const fetchCharacters = () => async dispatch => {
    const response = await fetch('https://swapi.co/api/people/');
    const data = await response.json();
    const results = await data.results;
    dispatch({
        type: FETCH_CHARACTERS,
        payload: results
    });
}

After that in reduce

case FETCH_CHARACTERS :
            return {
                ...state,
                characters: action.payload
            }

To load this data to my component:

componentDidMount() {
        this.props.fetchCharacters();
    }

After this this.props.characters is an array of objects.

So I've been thinking how can I add pictures for each character? I'm thinking something like mapping over objects, adding new property to each one. And to assign right picture to character I'm thinking naming pictures 0.jpg, 1.jpg, and then in map function just doing somehing like:

character.pic = `link/${index}.jpg`;

Is it a good way of achieving this? Or is there a better way?

2
  • Is this question asking how to map or asking if your idea is a good idea? Commented Jul 5, 2018 at 11:11
  • 1
    the index does not sound like a permanent property of each character. Maybe extract the id number from the url property of each character. Commented Jul 5, 2018 at 11:13

1 Answer 1

0

you can not change props value. i am sharing 2 way that you can use.

One is

 const resultObj = {};
    resultObj.result = await data.results;
    resultObj.imgPath = "path of image"
 dispatch({
        type: FETCH_CHARACTERS,
        payload: resultObj
    });

Second is here

this.setState({characters:this.props.fetchCharacters})

Now you can add key in state

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.