DevGe
DevGe

Reputation: 1449

How to fix state mapping is not a function in React Native?

I am currently studying react native and I explore the process of rendering the api data in the list view. Right now I have already the api data however when I tried mapping the array it says.

TypeError: this.state.readings.map is not a function. (In 'this.state.readings.map(function (value) { return console.log(value); })', 'this.state.readings.map' is undefined)

Here is the sample api:

Sample JSON

Inside of my ComponentDidMount:

componentDidMount() {
  
    fetch('http://myip:3000/api/readings/3')
    .then(response => response.json())
    .then(data => this.setState({readings:JSON.stringify(data)}))
}

My State:

this.state = {
  readings:[],
}

My Render:

render() {
    console.log(this.state.readings);
    return (
       
        {

            this.state.readings.map(value => {
                return (
                    console.log(value)
                )
            })

        }         
    )
}

Upvotes: 2

Views: 775

Answers (2)

Mohamed Abu Galala
Mohamed Abu Galala

Reputation: 438

I know this is using a functional component but it will be the same behavior

https://snack.expo.io/I0VJsF1z5

enter image description here

The problem maybe in this line .then(data => this.setState({readings:JSON.stringify(data)}))

Upvotes: 1

sakshya73
sakshya73

Reputation: 7162

EDIT

If the value of this.state.readings is [{"id":1,"AccountNo":"011-001","ConsName":"Jenny Fox.","Address":"Pacific Triad Road."}].

Then this code should work.

And as your data is loading async. You can add a check for this.state.readings before mapping it.

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      readings: [
        {
          id: 1,
          AccountNo: "011-001",
          ConsName: "Jenny Fox.",
          Address: "Pacific Triad Road."
        }
      ]
    };
  }
  render() {
    return (
      this.state.readings.length &&
      this.state.readings.map((value) => {
        console.log(value);
        return <div>{value.Address}</div>;
      })
    );
  }
}

ref : https://codesandbox.io/s/ancient-cdn-5695m?file=/src/App.js:51-484

Upvotes: 0

Related Questions