saeed
saeed

Reputation: 97

map an array in componentDidMount and render

i'm traying to map an array in componentDidMount and render it but it doesn't show anything can anyone help me please?

componentDidMount() {
  baseUrl
      .get("/api/v1/bases")
        .then((response) => {
          const data = response.data.data.data.data;
          console.log(data)
             const items = data.map((item) => {
               return (
                 <div>
                   <tr key={item.id}>
                     <td scope="row">{item.id}</td>
                     <td scope="row">{item.name}</td>
                     <td scope="row">
                       <button className="btn btn btn-outline-danger m-1 my-2 my-sm-0">
                         حذف
                       </button>
                       <Link
                         id={item.id}
                         to={`/Bases/edit/${item.id}`}
                         className="btn btn btn-outline-warning m-1 my-2 my-sm-0"
                       >
                         ویرایش
                       </Link>
                     </td>
                   </tr>
                 </div>
               );
             });
          })
      .catch((err) => {
        console.log(err);
      });
}

and i am trying to render it like this code inside table

</tr>
          {this.items}
        </tbody>

it is just part of code

Upvotes: 1

Views: 263

Answers (2)

marcobiedermann
marcobiedermann

Reputation: 4933

componentDidMount / useEffect are used to hook into the component's lifecycle. They are not meant to render/return any JSX elements. You could transform/map your data within componentDidMount and update the local component state which can then be used in render to display your data

class Component {
  state = [];

  async componentDidMount() {
    const items = await fetch()

    const mappedItems = items.map(item => item)

    this.setState(items)
  }

  render() {
    <ul>{this.state.map(item => (
      <li key={item.id}>
        {item}
      </li>
    ))}
    </ul>

  }
}

Upvotes: 2

Mohamed Ibrahim
Mohamed Ibrahim

Reputation: 57

Just call your API in ComponenDidMount lifecycle and display your data into render function

Upvotes: 1

Related Questions