John Ezkiel
John Ezkiel

Reputation: 11

Convert array to string react

I want to convert the following array (userNameApp) into string so I can insert the following array into the database as a string

        var userInfo = JSON.parse(window.localStorage.getItem('current-session'));
        const userNameApp = useState(userInfo['fname'] + " " + userInfo['lname']);
        console.log(userNameApp);

In the console log, the result is First Name + Last Name. When inserting in the database, I will post it like this

 Axios.post("http://localhost:3001/insertActiveUser", {userNameApp: userNameApp}))

Inside the database schema/model, the type of Value is string.

const mongoose = require("mongoose");
const User Details = new mongoose.Schema(
  {
    Username: String,
  },
  {
    collection: "AppointmentDetails",
  }
);

Upvotes: 0

Views: 291

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53525

The definition of userNameApp should be fixed to:

const [userNameApp, setUserNameApp] = useState(userInfo['fname'] + " " + userInfo['lname']);

Explanation

What returns from useState is an array of two values: the first value is the value we want to be able to set and use, and the second value is the set function.

If we'll want to re-set the variable userNameApp the correct way of doing it will be: setUserNameApp(newValue).

The value that we pass to useState will be the initial value.

Upvotes: 1

John Ezkiel
John Ezkiel

Reputation: 11

What I did is

 var userInfo = JSON.parse(window.localStorage.getItem('current-session'));
 var getUserName = JSON.stringify(userInfo['fname'] + " " + userInfo['lname'])
 const userNameApp = JSON.parse(getUserName)

Upvotes: 0

Related Questions