How to use a component's method to alter an object in another component? [React]

Viewed 86

I have a simple app with 3 React components stacked on top of another:

function App() {
  return (
    <Fragment>
      <div className="container">
        <ListSuppliers/>
        <InputContact/>
        <ListContact/>
      </div>

    </Fragment>
  );
}

In my ListSuppliers component I have a dropdown menu, in my InputContact component I have an input form, and in my ListContact I have an html table like so:

return <Fragment>
        <h1>List Contact</h1>

        <table className="table mt-5">
            <thead>
                <tr>
                    <th>Contact Name</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody>
                {contacts.map(contact => (
                    <tr key={contact.contact_id}>
                        <td>{contact.contact_name}</td>
                        <td><EditContact contact={contact}/></td>
                        <td><button className="btn btn-danger" onClick={()=> deleteContact(contact.contact_id)}>Delete</button></td>
                    </tr>
                ))}
                
                  
            </tbody>
  </table>

    </Fragment>

I want my html table in the ListContact component to be populated based on the selection from the menu in the ListSuppliers component:

//Select function

    const chooseSupplier = async (id) => {
        try {
            const response = await fetch(`http://localhost:5000/contact_supplier/${id}`,{
                method: "GET"
            });

            const jsonData = await response.json();

            
            console.log(jsonData);
            
        } catch (err) {
            console.log(err.message);
        }
    }

//Route

app.get("/contact_supplier/:id", async (req, res) => {
    try {

        const {id} = req.params;
        const contact = await pool.query('SELECT * FROM contact WHERE supplier_id = $1 ORDER BY contact_id ASC', [id]);


        res.json(contact.rows);

    } catch (err) {
        console.error(err.message);
    }
})

So far I am able to receive the query that I need in json format, however I'm not sure how to query from one component target to an object in another in this case.

1 Answers

You need to maintain the state in the parent component (here - App.js) for const [state,setState] = useState() and then pass the state and setState to the children where they can access them and call them.

Related