0
votes

I'm trying to loop through an array and fetch those results to display individually on my site but I keep getting the following error message:

TypeError: this.props.fetched.map is not a function

Not sure why I'm getting the error. Any ideas?

This is the code I'm currently working on:

import React from "react";
import "isomorphic-unfetch";

export default class HomePage extends React.Component {
  static async getInitialProps() {
    const todoIdList = [1, 2, 3, 4];
    for (const id of todoIdList) {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
      const todo = await response.json();
      return { fetched: todo.title };
    }
  }

  render() {
    return (
      <>
        <div>
          {this.props.fetched.map((datafetch, index) => (
            <p>{datafetch}</p>
          ))}
        </div>
      </>
    );
  }
}
2
what is the response from the api call ?Mohammad Faisal

2 Answers

0
votes

here you are calling this url https://jsonplaceholder.typicode.com/todos/${id} which will return you an object.

you are setting your state like this return { fetched: todo.title }; that means your fetched variable is now holding a string value.

but map function of javascript only works on arrays. as a result you are getting this error.

you can try something like this

    const todoIdList = [1, 2, 3, 4]; 
    const todoTitles = []
    for (const id of todoIdList) {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
      const todo = await response.json(); 
      todoTitles.push(todo.title)
      
    }
    return { fetched: todoTitles };
  }
0
votes

You are trying to iterate an object using map.

If you want to use map, you need to transform it firstly. Then, you can try something like:

{
    let aux = [];
    for (let [key, value] of Object.entries(this.props.fetched)) {
        aux.push(value);
    }

    aux.map((datafetch, index) => (
        <p>{datafetch}</p>
    ));
}