-5

trying to use the handle submit function to change the isAuthinticated to true from false thats on the main app.js file thats using react router.. all of the redux examples i look at are all using an app js file that has the onclick function on it not react router. thank you if you can help

function App () {
    return (
      <Router>
      <div>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/signup" component={Signup} />
          <PrivateRoute 
          exact path="/mainpage" 
          component={MainPage} 
          isAuthenticated={false}
          />
        </Switch>
      <Footer />
      </div>
    </Router>
    );
  }
export default App;

my login.js that has the click event

const Login = () => {
  const history = useHistory()
  const [state, setState] = useState({
    email: '',
    password: ''
   });
  
  const [validate, setValid] = useState({
   validateEmail: '',
   validatePassword: '', 
  }) 
  
  
const handleInputChange = event => setState({
    ...state,
    [event.target.name]: event.target.value,
  })

  const handleSubmit = user => {
    if(state.password === ''){
     setValid({validatePassword:true})
    }
    if(state.email === '' ){
     setValid({validateEmail:true})
    }

    axios.post(`auth/login`, state )
    .then(res => {
      console.log(res);
      console.log(res.data);  
      if (res.status === 200 ) {
        history.push('/mainpage');
      }  
    })
    .catch(function (error) {
      console.log(error);
      alert('Wrong username or password')
      window.location.reload();
    });
  }


  // console.log('state', state)
  const {email, password } = state

  const [popoverOpen, setPopoverOpen] = useState(false);

  const toggle = () => setPopoverOpen(!popoverOpen);
 
    return (
    <>
      <Container>
        <Row>
          <Col>
          <img src={logo} alt="Logo" id="logo" /> 
            <Button id="Popover1" type="button">
               About Crypto-Tracker
            </Button>
          <Popover placement="bottom" isOpen={popoverOpen} target="Popover1" toggle={toggle}>
            <PopoverHeader>About</PopoverHeader>
            <PopoverBody>Your personalized finance app to track all potential cryptocurrency investments</PopoverBody>
          </Popover>
          </Col>
          <Col sm="2" id="home" style={{height: 500}}>
            <Card body className="login-card">
              <Form className="login-form">
                <h2 className="text-center">Welcome</h2>
                <h3 className="text-center">____________</h3>
                <FormGroup>
                  <Label for="exampleEmail">Email</Label>
                  <Input invalid={validate.validateEmail}  onChange = {handleInputChange} value = {email} type="email"  required name="email" placeholder="email" />
                  <FormFeedback>Please enter email</FormFeedback>
                </FormGroup>
                <FormGroup>
                  <Label for="examplePassword">Password</Label>
                  <Input invalid={validate.validatePassword}   onChange = {handleInputChange} value = {password} type="password" required name="password" placeholder="password"/>
                  <FormFeedback>Please enter password</FormFeedback>
                </FormGroup>
                <Button  onClick={()=> handleSubmit(state)} className="but-lg btn-dark btn-block">Login</Button>
                <div className="text-center pt-3"> or sign in with Google account</div>
                <Loginbutton />
                <div className="text-center">
                  <a href="/signup"> Sign up</a>
                  <span className="p-2">|</span>
                  <a href="/ForgotPw">Forgot password</a>
                </div>
              </Form>
            </Card>
          </Col>
        </Row>
      </Container>
    </>
    );
  }

export default Login;

code

authslice.js using asyncthunk

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from '../../../server/routes/authRoutes'

const fetchAuth = createAsyncThunk(
    'auth/login',
    async (userId, thunkAPI) => {
      const response = await userAPI.fetchById(userId)
      return response.data
    }
  )

  const authSlice = createSlice({
    name: 'isAuthenticated',
    initialState: {
      value: false,
    },
    reducers: {
    //   Authenticated: state => {
        // Redux Toolkit allows us to write "mutating" logic in reducers. It
        // doesn't actually mutate the state because it uses the Immer library,
        // which detects changes to a "draft state" and produces a brand new
        // immutable state based off those changes
        // state.value = true;
    //   },
    },
    extraReducers: {
        [fetchAuth.fulfilled]: state  => {
            // Add user to the state array
                state.value = true
          },
        [fetchAuth.rejected]: state => {
            // Add user to the state array
            state.value = false
        }
    }
  });

  dispatch(fetchUserById(123))
  
//   export const { increment, decrement, incrementByAmount } = counterSlice.actions;
Aro Parada
  • 82
  • 9
  • @AjeetShah added code – Aro Parada Mar 02 '21 at 03:46
  • redux toolkit documentation doesnt show using react router from what i see. i only see the on click fuction being used directly with the app.js file unlike mine where the event is in another file – Aro Parada Mar 02 '21 at 05:56
  • does that mean i can still use them together – Aro Parada Mar 02 '21 at 07:25
  • na im not using that this is my repository https://github.com/jamescbaldwin/react-finance/tree/aro – Aro Parada Mar 02 '21 at 21:22
  • yeah i put router/switch/route in the app.js. ive just been watching redux videos all day to understand it cuz i have this due tommorrow morning. but basically i just need the private route to change to true from false once the user logs in which is an event that happens in the login.js component – Aro Parada Mar 02 '21 at 21:33
  • 1
    Do this: **1.** Create a new React Project using this official Redux Toolkit template: https://github.com/reduxjs/cra-template-redux#usage **2.** Run it locally and play with it 3. Look how they have done Store Setup 4. Copy code for Store setup and use that to setup store in your project. 5. Create Slice (async action and extraReducer) : https://redux-toolkit.js.org/api/createAsyncThunk : use this asyncThunkAction to make AUTH HTTP call and on success, store a `boolean` like `logged: true/false` 6. In your private route component, **select** the `logged` boolean value from Store 7. Done! – Ajeet Shah Mar 02 '21 at 21:41
  • wait do i clone that? – Aro Parada Mar 02 '21 at 21:50
  • 1
    with step 5 should i import axios instead of the " import { userAPI } from './userAPI' " that they have in the asyncThunk example – Aro Parada Mar 02 '21 at 22:23
  • added the async thunk file i tried how does it look? @AjeetShah – Aro Parada Mar 02 '21 at 23:19
  • 1
    https://stackoverflow.com/a/62964704/2873538.Yes use axios instead of userAPI – Ajeet Shah Mar 03 '21 at 01:49
  • Have you solved it? – Ajeet Shah Mar 03 '21 at 17:59
  • not yet i had to do a hard reset because my connection to the database wasnt working. – Aro Parada Mar 04 '21 at 21:47

2 Answers2

2

This would be easy to achieve if you use some kind of global store to store such values. Typical options include Redux, Mobx, etc.

Define your isAuthenticated variable as a global store variable. mutate its value using corresponding package methods like Redux dispatch events or similar from your functions anywhere else in the app.

Jibin Bose
  • 542
  • 2
  • 8
1

You can try it using Redux, creating a store to the login variables, and sharing it with the component App.js.