1

i am trying to set logged in user . using reducer. Errors are :

Unexpected token && Syntax Error

Error on line switch(action.type) or error in brackets not properly closing i do not know
either it will use : or = in reducer initialize and in initialState

StackOverflow : It looks like your post is mostly code; please add some more details.

me: i have enough detail which i shared i do not know more than above

 import React from 'react';
    import {View, StyleSheet, Text} from 'react-native';
    import {NavigationContainer} from '@react-navigation/native';
    import {createStackNavigator} from '@react-navigation/stack';
    import { AuthStackNavigator } from './navigators/AuthStackNavigator';
    import { AuthContext } from './context/AuthContext';
    import  axios  from "axios";
    import { BASE_URL } from './config';
    import { sleep } from './utils/sleep';
    import { createAction } from './utils/createAction';
    const RootStack = createStackNavigator();
    
    export default function ()
    {
      
      const [ state, dispatch ] = React.useReducer(
        reducer : ( state: { user: * }, action ) =>
        {
          switch ( action.type )
          {
            case 'SET_USER':
              return {
                ...state,
                user: { ...action.payload },
              };
            default:
              return state;
          }
        },
        initialState : {
          user: undefined,
        }
      );
    
      const auth = React.useMemo( () => ( {
    
        login: async (email,password) =>
        {
              
    const options = {
      method: 'post',
      url: `${BASE_URL}/auth/local`,
      data: {
        identifier: email,
        email,
        password,
      },
      transformResponse: [
        (data) => {
          // transform the response
          return data;
        },
      ],
    };
    await sleep(2000);
    
    // send the request
    const {data}= axios( options );
    
          const user = {
            email: data.user.email,
            token: data.jwt,
          };
       dispatch(createAction(type:'SET_USER',user))
        },
    
    
        logout: () =>
        {
          console.log( 'logout' );
        },
    
    
        register:async (email,password) =>
        {
    const options = {
      method: 'post',
      url: `${BASE_URL}/auth/local/register`,
      data: {
        user: email,
        email,
        password,
      },
      transformResponse: [
        (data) => {
          // transform the response
    
          return data;
        },
      ],
    };
    await sleep(2000);
    
    // send the request
        
    
    
          // console.log( 'register' );
          // await axios.post(url:`${BASE_URL}/auth/local/register`, data:{
          //   username: email,
          //   email,
          //   password,
          // } );
        },
      } ),
      );
    
    
    console.log(state.user)
    
      return (
        <AuthContext.Provider value={auth}>
          <NavigationContainer>
            <RootStack.Navigator screenOptions={ { headerShown: false } }>
              <RootStack.Screen name={ 'AuthStack' } component={ AuthStackNavigator } />
            </RootStack.Navigator>
          </NavigationContainer>
        </AuthContext.Provider>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
user10
  • 15
  • 6
  • Possible typo? Remove the "reducer : " in front of your reducer function in the `useReducer` hook. It's also not clear what `{ user: * }` is about. Are you trying to provide *some* initial state or something? "Initial state" would be the second argument passed to `useReducer`. – Drew Reese Dec 29 '20 at 06:59
  • Thanks @DrewReese i remove reducer now error in below line where initialState set here initialState : { user: undefined, }, error is : the type cast expression is expected to be wrapped with parentheses – user10 Dec 29 '20 at 07:06
  • Ahhh, probably want to remove also "initialState : " as well, it isn't valid javascript. – Drew Reese Dec 29 '20 at 07:09
  • OK . Then How to set initialState ? – user10 Dec 29 '20 at 07:10
  • Have you read the official react docs for [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer). Your initial state is simply the second argument passed to the `useReducer` hook. I.E. `const [state, dispatch] = React.useReducer(reducerFunction, initialStateObject);`. – Drew Reese Dec 29 '20 at 07:11
  • Thanks @DrewReese . I try . can please tell me how i can do with above reducer ? i am beginner . doc looks simple – user10 Dec 29 '20 at 07:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/226545/discussion-between-drew-reese-and-user10). – Drew Reese Dec 29 '20 at 07:32

1 Answers1

2

If I understand your error and issue correctly it appears to be related to how you are trying to define your useReducer hook arguments. You appear to be attempting to define object keys, but you are not defining an object. The useReducer hook function simply consumes up to 3 arguments.

useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);

Generally you only need the first two, i.e. your reducer function and the initial reducer state value. You can read further in the docs about the third argument for lazy initialization.

const [state, dispatch] = React.useReducer(
  (state, action ) => { // <-- reducer function
    switch (action.type) {
      case 'SET_USER':
        return {
          ...state,
          user: { ...action.payload },
        };
      default:
        return state;
    }
  },
  { user: undefined }, // <-- initial state object value
);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181