简体   繁体   中英

How do I use a JSON file as a database for dummy users in my React Hooks e-commerce app?

I am creating a frontend dummy e-commerce app. I have created a login page, and the idea is to link the JSON database of users which all have a unique username, password and ID and when you try to login with the parameters you get the Login successful message if there is a user with those parameters in the JSON, and if there is not you get the Fail message. Below is my source code for the login page. For now I have just made a simple if user = user@gmail.com and password = user password, then you get the success message, but the idea is to use the database for multiple user options. The JSON file will be a basic array of user objects.

PS stack overflow wont let me post the code unless I put constant and be grammatically correct so I had to separate the use State use navigate and so on

const Login = () => {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const [valid, setValid] = useState(false)
    const [success, setSuccess] = useState(false)

    const navigate = useNavigate()

    const handle Submit = (e) => {
      if (email === 'user@gmail.com' && password === 'user password') {
        setValid(true)
        setSuccess(true)
        setTimeout(() => {
          navigate('/')
        },3000)
      }
      e.preventDefault()
    }
}

I will imagine your users array is like so per your description

const users = [
    { id: 1, name: 'John',email: 'user1@gmail.com', password: '123456' },
    { id: 2, name: 'Pete' , email: 'user2@gmail.com', password: '123456' },
    { id: 3, name: 'Mary' , email: 'user3@gmail.com', password: '123456' },
];

your submit function will be like so

const handleSubmit = (e) => {
    e.preventDefault();
    const user = users.find((user) => user.email === email && user.password === password);
    if (user) {
       // login success
    }
    else {
         // login failed
    }
}

this will check if the user info exists in your JSON data or not you can replace the login success comment and failure wth your specific logic

You can install the package json-server https://github.com/typicode/json-server or maybe another package that does the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM