1

I'm new to react native, so please be kind! I am trying to populate a Flatlist using a JSON.

Below is my JSON data

{
   "h1":{
      "baseprice":899,
      "description":"Upto Waist length Hair",
      "imageUrl":"https://i.imgur.com/0IgYzAv.jpg'",
      "price":799,
      "time":"25 min",
      "title":"Nourishing Hair Spa",
      "type":"Service"
   },
   "h2":{
      "baseprice":899,
      "description":"Touch Up of length less than 4 inches",
      "imageUrl":"https://i.imgur.com/q7ts4PZ.jpg",
      "price":799,
      "time":"45 min",
      "title":"INOA Root Touch Up",
      "type":"Service"
   }
}

Here is the code that I used to push the JSON data in to my Flatlist

export default class Office extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
    };
  }

  componentDidMount() {
    return fetch("https://stylmate1.firebaseio.com/hair.json")
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
        console.log(dataSource);
      })
      .catch((error) => {
        console.error(error);
      });
  }
  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, paddingTop: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.dataSource}
          renderItem={(item) => <Text>{item.title}</Text>}
        />
      </View>
    );
  }
}

As soon as I refresh the App I get an error Can't find variable : dataSource But if I console.log(responseJson); then I get the complete JSON object.

I don't know what am I doing wrong here. Please help me in fixing this.

Sva
  • 135
  • 1
  • 12

3 Answers3

1

Your FlatList is supposed to look like this:


return (
      <View style={styles.container}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item[1].title}</Text>}
        />
      </View>
    );

You have to destructure the item in order to use it.

Output:

enter image description here

Working Example code:

import React, { useState, useEffect } from 'react';
import { Text, View, FlatList, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  const [dataSource, setData] = useState([]);
  useEffect(() => {
    fetch('https://stylmate1.firebaseio.com/hair.json')
      .then((response) => response.json())
      .then((responseJson) => {
        setData(responseJson);
        console.log(responseJson);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);
  return (
    <View style={styles.container}>
      {dataSource ? (
        <FlatList
          data={Object.entries(dataSource)}
          renderItem={({ item }) => (
            <View style={{ padding: 10 }}>
              <Card>
                <Text style={styles.paragraph}>{item[1].title}</Text>
              </Card>
            </View>
          )}
        />
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Expo Snack Live Demo

Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41
  • code is already updated to fetch it from url – Ketan Ramteke Nov 30 '20 at 16:22
  • Yes sir! Many Thanks, you are are Godsend. – Sva Nov 30 '20 at 16:39
  • Glad it helped, happy coding. – Ketan Ramteke Nov 30 '20 at 16:42
  • Hello Ketan, I just want to bring into your notice that now I getting "JSON Can't perform a React state update on an unmounted component" error. Can you kindly advise how to fix this. Check it here : [link](https://stackoverflow.com/questions/65162525/while-fetching-data-from-json-cant-perform-a-react-state-update-on-an-unmounted) – Sva Dec 06 '20 at 20:22
0

The Error happens because you are trying to log dataSource which is wrong it should be this.state.dataSource.

console.log(dataSource);

change it to

console.log(this.state.dataSource);

in your .then() block

yesIamFaded
  • 1,970
  • 2
  • 20
  • 45
0

firstly,

console.log(dataSource);

should change to

console.log(this.state.dataSource);

However, you may not get the correct console.log since set state is async. You get better and accurate answer with responseJson

Secondly, flatList requires an array of objects structure, you need to convert them using the following methods. I moved your "h1", and "h2" into the object and label them as key.

const original = {
   "h1":{
      "baseprice":899,
      "description":"Upto Waist length Hair",
      "imageUrl":"https://i.imgur.com/0IgYzAv.jpg'",
      "price":799,
      "time":"25 min",
      "title":"Nourishing Hair Spa",
      "type":"Service"
   },
   "h2":{
      "baseprice":899,
      "description":"Touch Up of length less than 4 inches",
      "imageUrl":"https://i.imgur.com/q7ts4PZ.jpg",
      "price":799,
      "time":"45 min",
      "title":"INOA Root Touch Up",
      "type":"Service"
   }
}

const newArray = Object.keys(original).map( key => ({...original[key], key }))

console.log(newArray)
Someone Special
  • 12,479
  • 7
  • 45
  • 76