Home > other >  ReactJS parse data fetch from API to another component
ReactJS parse data fetch from API to another component

Time:10-19

I have data that getting from API in one component. For example, I have a file called Inventory.js

export function Inventory() {
  const url = "http://localhost:8080/api/inventory/products";
  const [product, setProduct] = useState(null);

  useEffect(() => {
    axios
      .get("http://localhost:8080/api/inventory/products")
      .then((response) => {
        setProduct(response.data);
      });
  }, [url]);
  console.log(product);

My variable product will now consist of all the data from API.

Now I have another file ProductEditForm.js

export const ProductEditForm = ({ onSubmit }) => {
    console.log(product) <-- Not working here?
}

How can I get product data from Inventory.js to ProductEditForm.js?

CodePudding user response:

    make an API call in parent component and pass the data as props to both above component
    
    //demo
    
    //parent component
    
    export default function App(){
    const [data,setData]=React.useState();
useEffect(() => {
    axios
      .get("http://localhost:8080/api/inventory/products")
      .then((response) => {
        setData(response.data);
      });
  }, [url]);
     return(
    <div>
    <Inventory data={data}/>
    <ProductEditForm data={data}/>
    </div>
    )
    }

//inventory
export default function Inventory({data}){
return(
<div></div>)
}

CodePudding user response:

Pass the data from parent to child

<ProductEditForm product={product}/>


export const ProductEditForm = ({ onSubmit, product}) => {
    console.log(product) 
}
  • Related