-1

I have 4 separate input send a request for update user data, So I make a function that takes an argument and passes it to body But it's not working I got 500 status error!

But when I declare the body name it's work for one input.

const sendReq = (bodyName) => {
    let AuthStr =
      'Bearer ...';

    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };
    Api.post(
      '/edit/user',
      {
        email: bodyName, // here it's work "but i want this be more dynimacly."
       // bodyName: bodyName, // error 500
      },
      {
        headers,
      },
    ).then((res) => {
      console.log(res.data);
    });
  };


// for update email

  const updateEmail = (newEmail) => {
    if (validateEmail(newEmail)) {
      setError('');
      sendReq(email);
      console.log('yay!');
    } else {
      setError('error....');
    }
  };

// password
const updatePassword = () => {
    ....
    sendReq(password);
}

// and so on...
Oliver D
  • 2,579
  • 6
  • 37
  • 80
  • Duplicate: https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal (although it took reading the OP's self-answer before I could understand the question well enough to determine that) – Quentin Aug 29 '20 at 09:52
  • Yes, i solved and add an answer :) if you want I can delete the question without downvote :)) – Oliver D Aug 29 '20 at 09:53

2 Answers2

0

I solve it :) I adding 2 arguments first one for the property name and second argument for property value like this:

const sendReq = (bodyName, bodyVal) => {
    let AuthStr =
      'Bearer ..';

    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };

    let body = {};
    body[bodyName] = bodyVal;
    console.log(body);
    Api.post('/edit/user', body, {
      headers,
    })
      .then((res) => {
        console.log(res.data); // works :"D
      })
      .catch((err) => console.log(err));
  };

And here's when I calling it.

sendReq('email', email);
sendReq('password', password);
Oliver D
  • 2,579
  • 6
  • 37
  • 80
0

This is a backend issue, API expects "email" variable in request body, not bodyName. That's Why it throws error.

sivarasan
  • 320
  • 3
  • 10