Hello today I started working with redux so I am a beginner and I want to make my register request the API Is working perfectly I tested it with postman and also with normal fetch on a component without redux and worked so API is not the problem.
Basically, I want to send user data and get the token back I get 404 not found error in the console here is my code =>
import React, { useState } from 'react';
import './App.css';
import { Provider, connect } from 'react-redux'
import store from './store'
import { register } from './actions/auth'
import PropTypes from 'prop-types';
function App({ register }) {
const [username, setUsername] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
return (
<>
<input placeholder="email" onChange={(e) => { setEmail(e.target.value) }} />
<input placeholder="username" onChange={(e) => { setUsername(e.target.value) }} />
<input placeholder="password" onChange={(e) => { setPassword(e.target.value) }} />
<button onClick={() => { register({ username, password, email }) }}>register</button>
</>
);
}
//todo proptypes
register.PropTypes = {
register: PropTypes.func.isRequired
}
export default connect(null, { register })(App);
// import
import axios from 'axios'
import { REGISTER_FAIL, REGISTER_SUCCESS } from './types'
//register user
export const register = ({ name, email, password }) => async dispatch => {
const config = {
headers: {
"Content-Type": "application/json"
}
}
const body = JSON.stringify({ name, email, password })
try {
const res = await axios.post('http://localhost:3000/api/register', body, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
} catch (error) {
dispatch({
type: REGISTER_FAIL
})
}
}
import { REGISTER_FAIL, REGISTER_SUCCESS } from '../actions/types'
const initialState = {
token: localStorage.getItem("token"),
isAuthenticated: null,
user: null
}
export default function (state = initialState, action) {
const { type, payload } = action
switch (type) {
case REGISTER_SUCCESS:
localStorage.setItem("token", payload.token);
return {
...state,
...payload,
isAuthenticated: true
}
case REGISTER_FAIL:
localStorage.removeItem("token");
return {
...state,
token: null,
isAuthenticated: false
};
default:
return state
}
}