Search code examples
javascriptreactjsreact-componentreact-state-management

How to change any function Component's state from another function?


React 16.8 brought the state and setState functionality into function based Component.

My question is:
In the case of Function based component is there any way to change the state outside the function ?

Example:

import {useState} from 'react';
import Axios from 'axios';


function fetch_all_products(){
    Axios.get(url)
        .then(
            response => {
                let data = response.data;

                //FROM HERE I WANT TO SET THIS DATA INTO SHOP COMPONENT
                // STATE (i.e, products) AND RE RENDER THE SHOP COMPONENT
            }
        )   
}



export default function Shop(){
    const[products, setProducts] = useState(products['Rice','Oil']);

    let all_products = products.map( product => {
        return(
            <li>product</li>
        )
    });

    return(
        <>
            <h2>The Grocery Shop </h2>
            <button onClick={fetch_all_products}>See All Products </button>
            <ul>
                {all_products}
            </ul>
        </>
    )
}

I want to change the Shop component's state (products) outside the function by using 'fetch_all_products' function.


Solution

  • Finally I come up with an easy solution.

    Instead using the essential function outside the component function, I used it inside the component function ('fetch_all_products' used inside 'Shop').

    [There was a silly syntactical mistake in my question, that is also corrected here]

    Code:

    import { useState } from 'react';
    import Axios from 'axios';
    
    export default function Shop() {
      const [products, setProducts] = useState(['Rice', 'Oil']);
    
      function fetch_all_products() {
        Axios.get(url).then((response) => {
          let data = response.data;
          setProducts(data);
        });
      }
    
      let all_products = products.map((product) => <li>{product}</li>);
    
      return (
        <>
          <h2>The Grocery Shop </h2>
          <button onClick={fetch_all_products}>See All Products </button>
          <ul>{all_products}</ul>
        </>
      );
    }
    

    Thank you everybody who tried to help me in different ways.