0

Instead of using a static array below, I want to use a json file, so I can update the data myself. The cards array is used for the DeckSwiper component (see: https://docs.nativebase.io/Components.html#deckswiper-def-headref )

const cards = [
      {
        text: 'text1',
        name: '1',
      image: {
            uri: 'http://www.xxx.xx/2.jpg'
        }
      },
        {
        text: 'text2',
        name: '2',
      image: {
            uri: 'http://www.xxx.xx/2.jpg'
        }
      },];

The json I want to fetch looks like this.

{ 
   "text1": "text1",
     "name1": "1",
     "image1": {
        "uri1": "http://www.xxx.xx/1.jpg"
    },
   "text2": "text2",
     "name2": "2",
     "image2": {
        "uri2": "http://www.xxx.xx/2.jpg"
    }
}

So I want to use 'fetch' to fetch the json file. First by initiating the array in the constructor, like this.

 constructor() {
     super();
    this.state = {
      active: 'true',
       response: [{text: '', name: '', image: {uri: ''}}],
      } 
  }

Then I use 'fetch' in componentDidMount() like this.

  componentDidMount() {

         fetch("http://www.xxx.xx/test.json", { method: 'get' })
         .then((response) => response.json())
      .then((responseJson) => {
               this.setState({ response: responseJson });
            });
  } 

How can I convert the json to an array? Because in the code below the dataSource needs an array instead of an object.

render() {
    return(
    ...
   <DeckSwiper dataSource={this.state.response}
    ...    
    />
     );
 }
  • Are you getting an error message? What is it (the exact wording)? – Robert Harvey Nov 21 '17 at 20:57
  • I only get warnings, like: "Warning: Failed prop type: Invalid prop `dataSource` of type 'object' supplied to 'DeckSwiper', expected 'array'. And 'source.uri should not be an empty string' – ByronSchuurman Nov 21 '17 at 21:00
  • 1
    OK, what does the JSON that you're retrieving look like? Please include that (or a sufficiently representative sample) in your question. – Robert Harvey Nov 21 '17 at 21:16
  • I've updated my question by adding the JSON code sample. – ByronSchuurman Nov 21 '17 at 21:22
  • 1
    `{ "text": "...", "text": "..." }` isn't valid json. Are you sure file isn't already saving the data as an array? – stealththeninja Nov 21 '17 at 21:23
  • The json keys are indeed duplicate. I wonder what keys I have to use to mimic the cards array. However, when I adjust the keys and have a valid json I still get the same warnings and cards remain empty. – ByronSchuurman Nov 21 '17 at 21:30
  • 1
    Just do `console.log(responseJson)` so you can see what's being returned...you're probably getting an object returned with the array in there. – Matt Aft Nov 21 '17 at 22:01

0 Answers0