0

How can I solve this problem?

Warning: Cannot update a component (`App`) while rendering a different component (`Profile`). To locate the bad setState() call inside `Profile`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
    at Profile (http://localhost:3000/static/js/bundle.js:131:5)
    at div
    at App (http://localhost:3000/static/js/bundle.js:33:74)

I want the state in component App to be setState in component Profile via the getName function. this is my code

import { useState } from "react";
import "./App.css";
import Profile from "./Profile";

function App() {
  const [name, setName] = useState("Sophia");

  const getName = (name) => {
    setName(name);
  };

  return (
    <div className="App">
      <p>My name is : {name}</p>
      <Profile getName={getName}></Profile>
      <p>Profile My name is : {name}</p>
    </div>
  );
}

export default App;
import React from "react";

function Profile({ getName }) {
  getName("Isabella");
  return <div>Profile</div>;
}

export default Profile;
  • 1
    This link might help: https://stackoverflow.com/questions/62336340/cannot-update-a-component-while-rendering-a-different-component-warning – Bar Mar 25 '22 at 18:21

1 Answers1

0
import React from "react";

function Profile({ getName }) {
useEffect(()=>{
 getName("Isabella");
},[])
 
  return <div>Profile</div>;
}

export default Profile;


KeyvanKh
  • 311
  • 1
  • 6