AsyncStorage.getItem is giving this error in react native when added in useEffect what am I doing wrong here can anyone pls help me understand the error.
export default function Pregent_login(props) {
const [first, setfirst] = useState();
useEffect(() => {
console.log('route.params ==>', props.route.params);
const value = AsyncStorage.getItem('token');
setfirst(value);
}, []);
Check the below code:
export default function Pregent_login(props) {
const [first, setfirst] = useState();
useEffect(() => {
console.log('route.params ==>', props.route.params);
AsyncStorage.getItem('token').then(token => {
setfirst(token);
})
}, []);
Please try using this way
AsyncStorage.getItem('token').then(token => {
// again, the rest of your function should be in this block
})
More details Here
Related
I am new to react native and trying to create React Native context which will store array of objects. Context looks something like this:
import React, {useState, useCallback} from 'react';
export const NotificationContext = React.createContext({
notifications: [],
updateNotifications: () => {},
});
export default function NotificationContextProvider({children}) {
const [notifications, setNotifications] = useState([]);
const updateNotifications = n => {
notifications.push(n);
setNotifications(notifications);
};
const contextValue = {
notifications,
updateNotifications: useCallback(n => updateNotifications(n), []),
};
return (
<NotificationContext.Provider value={contextValue}>
{children}
</NotificationContext.Provider>
);
}
Now when I am trying to access the context, I am not getting the updated array value as desired.
var context = useContext(NotificationContext);
useEffect(() => {
(async () => {
console.log('Before', context);
console.log('Notification value', context.notifications);
context.updateNotifications([1]);
console.log('After', context);
})();
}, []);
I think you should pass dependencies variable context in useEffect
I faced this problem when updated my React Native version. I checked the documentation it says removeListener is deprecated.
useEffect(() => {
Keyboard.addListener("keyboardDidShow", keyboardDidShow);
Keyboard.addListener("keyboardDidHide", keyboardDidHide);
return () => {
Keyboard.removeListener("keyboardDidShow", keyboardDidShow);
Keyboard.removeListener("keyboardDidHide", keyboardDidHide);
};
}, []);
I did this like this:
useEffect(() => {
const unsubscribe_KeyboardDidShow = Keyboard.addListener("keyboardDidShow", keyboardDidShow);
const unsubscribe_keyboardDidHide = Keyboard.addListener("keyboardDidHide", keyboardDidHide);
return () => {
unsubscribe_KeyboardDidShow.remove();
unsubscribe_keyboardDidHide.remove();
};
}, []);
Faced this when updated my React Native version.
I'm developing a react native mobile app using UI Kitten. I'm still fairly new to both react native and UI kitten, so I am using the just the plain Javascript template VS the Typescript template.
I have a functional component screen as shown below. This screen is working just fine. Today I started REDUX implementation.
const RequestScreen = ({ navigation }) => {
// code removed for brevity
}
Within this screen I use the useEffect hook to fetch data from my API
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
getServices();
});
return () => {
unsubscribe;
};
}, [navigation]);
const getServices = async () => {
setLoading(true);
// helper function to call API
await getAllServices().then((response) => {
if (response !== undefined) {
const services = response.service;
setServices(services);
setLoading(false);
}
});
// update redux state
props.getAllServices(services);
};
// code removed for brevity
const mapStateToProps = (state) => state;
const mapDispatchToProps = (dispatch) => ({
getServices: (services) =>
dispatch({
type: Types.GET_SERVICES,
payload: { services },
}),
});
const connectComponent = connect(mapStateToProps, mapDispatchToProps);
export default connectComponent(RequestScreen);
On this line of code:
props.getAllServices(services);
I keep getting this error:
[Unhandled promise rejection: TypeError: undefined is not an object
(evaluating 'props.getAllServices')] at
node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch at
node_modules\regenerator-runtime\runtime.js:293:29 in invoke
Anytime I try to use "props" in code here. I run into errors. How do I get the props on this screen?
I tried changing the screen, as shown below, but that does not work either!
const RequestScreen = ({ navigation, props }) => {
// code removed
}
I was able to get the props object after changing the screen component as shown below.
const RequestScreen = ({ navigation, ...props }) => {}
i am getting error with props.title this is my code enter image description here
1: https://i.stack.imgur.com/Bjrb4.png and i am getting this error
enter image description here
navigation.Opendrawer not working...PFA...code
when i am clicking nothing is happening
It's wrong syntax, use this
const CustomHeader = (props) => {
const {title, home} = props;
....
props.navigation.goBack()
}
or
const CustomHeader = ({title, home, navigation}) => {
.....
navigation.goBack() // <== No props.navigation
}
Please specify what value is delivered to prop in CustomerHeder component.
<CustomerHeder title={"title"} isHome={"something"}/>
const CustomerHeder = (props) => {
const {title, isHome} = props
return ...
}
also You can try...
const CustomerHeder = ({title , isHome}) => {
return ...
}
I am new and i want to using react native to create android application so after creating project i installed redux and redux thunk and do every config that redux wants to work .
I create a action file :
export const GETSURVEYOR = 'GETSURVEYOR';
const URL = "http://192.168.1.6:3000/";
export const fetchSurveyor = () => {
return async dispatch => {
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
10000,
);
const response = await fetch(`${URL}GetSurveyorList`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({}),
signal: controller.signal
});
clearTimeout(timeout);
const resData = await response.json();
dispatch({
type: GETSURVEYOR,
surveyorList: resData.SurveyorList
});
}
}
after that i create reducer to handle this data :
import {GETSURVEYOR} from '../actions/surveyor'
const initialState = {
surveyorList: []
}
export default (state = initialState, action) => {
switch (action.type) {
case GETSURVEYOR:
return {
...state,
surveyorList: action.surveyorList
};
Now i am using by useSelector, useDispatch from 'react-redux .
import React, { useState, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import * as surveyorActions from '../store/actions/surveyor';
export default () => {
const [surveyorCount, setSurveyorCount] = useState(0);
const survayers = useSelector(state => state.surveyor.surveyorList);
const dispatch = useDispatch();
const loadSurvayer = useCallback(async () => {
await dispatch(surveyorActions.fetchSurveyor());
console.log('run use Callback');
console.log('returned :', survayers );
// setSurveyorCount(survayers.length);
}, [dispatch]);
useEffect(() => {
loadSurvayer();
}, [dispatch]);
return [loadSurvayer, surveyorCount];
}
When for first time this paged is rendered , of course that survayers is empty but after fetch data in action and set state to reducer , survayers nut to be an empty.
But i get empty still ? I am sure data is fetched from services but i got empty from survayers ?
LOG Running "RNAuditMngm" with {"rootTag":1}
LOG run use Callback
LOG returned : []
LOG run use Callback
LOG returned : []
if i change my useEffect code to this:
useEffect(() => {
loadSurvayer();
}, [dispatch,survayers]);
I fall to loop !!!! How could i change code without loop?
I think everything works fine, but you're not using the console.log in the right place. When you run the loadSurvayer the survayers is empty. It is empty even the second time because you are not passing it as a dependency in the useEffect hook. And like you said, if you pass it as a dependency, then it causes an infinite loop, and that's right because whenever the survayers change, that function will be called again and so on.
So, here's what you have to do:
Remove the dispatch dependency from your useEffect hook.
Change the console.log's outside of the loadSurvayer function.
Remove the await from the dispatch call because it is synchronous.
Here's how to modify your code to work the right way:
import React, { useState, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import * as surveyorActions from '../store/actions/surveyor';
export default () => {
const [surveyorCount, setSurveyorCount] = useState(0);
const survayers = useSelector(state => state.surveyor.surveyorList);
const dispatch = useDispatch();
const loadSurvayer = useCallback(async () => {
dispatch(surveyorActions.fetchSurveyor()); // Remove the `await`
console.log('run use Callback');
// setSurveyorCount(survayers.length);
}, [dispatch]);
useEffect(() => {
loadSurvayer();
}, []); // <-- remove the `dispatch` from here.
console.log('returned :', survayers ); // <-- Move the console log here
return [loadSurvayer, surveyorCount];
}
Improvement bonus and suggestion: remove the surveyorCount state variable because you don't actually need it as you can return the count directly.
import React, { useState, useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import * as surveyorActions from '../store/actions/surveyor';
export default () => {
// Remove the `surveyorCount`
//const [surveyorCount, setSurveyorCount] = useState(0);
const survayers = useSelector(state => state.surveyor.surveyorList);
const dispatch = useDispatch();
const loadSurvayer = useCallback(async () => {
dispatch(surveyorActions.fetchSurveyor()); // Remove the `await`
console.log('run use Callback');
// setSurveyorCount(survayers.length);
}, [dispatch]);
useEffect(() => {
loadSurvayer();
}, []); // <-- remove the `dispatch` from here.
console.log('returned :', survayers ); // <-- Move the console log here
//return [loadSurvayer, surveyorCount];
return [loadSurvayer, survayers.length]; // <-- Use `survayers.length` instead of `surveyorCount`
}
In useSelector shouldn't you read surveyerList like this state.surveyorList ?. your state doesn't have any object named surveyor but you are currently reading like state.surveyor.surveyorList