0

I export a JS object called Products to this file, just to replace a real API call initially while I am building/testing. I want to set the function's state to the object, but mapped. I have the component looking like this:

function App() {
  const [rooms, setRooms] = useState([]);
  const [days, setDays] = useState([]);
  const roomsMapped = products.data.map(room => ({
    id: room.id,
    title: room.title
  }))

  useEffect(() => {
    setRooms(roomsMapped);
  })

  return ( etc )

This returns the following error: Error: Maximum update depth exceeded.

I feel like I'm missing something really obvious here, but am pretty new to React and Hooks. How can I set this data before the component renders?

James Stewart
  • 869
  • 12
  • 33

5 Answers5

4

Just declare it as initial value of rooms

 const Component = () =>{
     const [rooms, setRooms] = useState(products.data.map(room => ({
         id: room.id,
         title: room.title
      })))
 }

You can also use lazy initial state to avoid reprocessing the initial value on each render

 const Component = () =>{
     const [rooms, setRooms] = useState(() => products.data.map(room => ({
         id: room.id,
         title: room.title
      })))
 }
Dupocas
  • 20,285
  • 6
  • 38
  • 56
2

Change useEffect to this

useEffect(() => {
    setRooms(roomsMapped);
  },[])
The_ehT
  • 1,202
  • 17
  • 32
0

With Lazy initialisation with function as a parameter of useState

import React, { useState } from "react";

function App() {
  const [rooms, setRooms] = useState(() => {
    // May be a long computation initialization
    const data = products.data || [];
    return data.map(({ id, title }) => ({ id, title }));
  });

  return (
    // JSX stuffs
  )
}
Tolotra Raharison
  • 3,034
  • 1
  • 10
  • 15
0

You can use default props for this.set initial value with empty list .

Muhammad Raheel
  • 617
  • 1
  • 6
  • 15
0

You are getting 'Error: Maximum update depth exceeded', because your useEffect function doesn't have dependency array. Best way to fix this is to pass empty array as the second argument to useEffect like this:

useEffect(() => {
    setRooms(roomsMapped);
  },[]) <= pass empty array here 

this will prevent component to re render, it you want your component to re render on props change you can pass the props in the array like this:

useEffect(() => {
    setRooms(roomsMapped);
  },[props.props1,props.props2])

here you can pass as many props as you want...

Bojan Mitic
  • 462
  • 5
  • 12