Skip to content
Advertisement

How to send a variable to Backend – Mern Stack

I am trying to get some records from Mongo db based on a query. I completed the Back-end and it works well with the Postman but I do not know how to send the variable for the query from react front end to the back end.

There is a Client model class and I want to retrieve all the clients with a specific company ID which I will be sending from Front end on a button click.

Controller.js

exports.viewSpecificClients = async(req,res)=>{
  const id = req.query.id;
  console.log(id);
    try{
      const clients = await Client.find({clientCompanyName: id});
      res.json({clients});
    }catch(err){
      console.log(err, 'clientsController.viewSpecificClients error');
      res.status(500).json({
        errorMessage: 'Please try again later'
      })
    }
};

Route

router.get('/', clientsController.viewSpecificClients);

I have to use Redux, so I tried do do this but I could only manage to display all the clients in the database (I do not know how to send the variable).

Action.js in Redux

export const getClients = () => async dispatch =>{
    try{
        const response = await axios.get('clients');
        dispatch({
            type: GET_CLIENTS,
            payload: response.data.clients
        });
    }catch(err){
        console.log('getClients api error:', err);
    }
}

Can you please help me on how I can send the company id from front-end using redux – that is I want help with how to change the action function and also what do I have to do in the main.js file when the button is clicked ?

Advertisement

Answer

if you have access to companyId at the front end, all you need to do is

 const response = await axios.get(`clients?id=${companyId}`);

assuming backend express is configured with query parser already.(by default)

may be you can have

const getClients = (companyId) => dispatch => {
  const response = await axios.get(`clients?id=${companyId}`);
  // above code here
}

let me know if you need further follow up.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement