why passing params do not refresh and have to refresh the new page update - react-native

i am trying to pass params to next page by calling id from previous
page. but when you enter the next page the data does not appear
immediately and you have to refresh the page which takes quite a long
time, and faithfully calling new data, what appears is the previous
data, you have to refresh the page to bring up new data. what is the
solution?
first page code
...//
onPress={() => {
setId(item.ID);
navigation.navigate('Rekap_Bencana', {
params: id
});
}}
...//
const [dataBencana, setDataBencana] = useState();
const [id, setId] = useState();
useEffect(() => {
getData();
}, []);
const getData = () => {
fetch('http://192.168.0.103/aplikasi/restapi.php?op=getDatabencana')
.then(response => response.json())
.then(json => {
// console.log(json);
setDataBencana(json);
// console.log(dataBencana);
});
};
params page code
const Rekap_Bencana = () => {
const route = useRoute();
const navigation = useNavigation();
const {params} = route.params;
useEffect(() => {
getData();
console.log(params);
}, []);
const [data, setData] = useState();
const getData = () => {
fetch('http://192.168.0.103/aplikasi/restapi.php?op=getBencanaDetail', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: params,
}),
})
.then(res => res.json())
.then(resp => {
setData(resp);
console.log(resp);
});
};

Related

how to fetch data from Api folder in next.js

I"m facing this problem, I store my submitted data in api folder from a page and i successfully can store it and when i console.log it I can see the data but the problem is when I try fetch it to a page where I want show all this data then I didn't get any result, it's shows empty object:
this is the page from where I submitted data to api folder/page
const handleSubmitAllData = async (e) => {
e.preventDefault();
const allData = {
addStory,
selectedVideoUrl,
};
console.log("AllNftData:", allData);
try {
const { data } = await axios({
url: "/api/uploadNftData",
method: "POST",
data: allData,
});
console.log("response Data", data);
} catch (error) {
console.log("Error", error);
}
router.push("/template/marketplace");
};
this is the api page where store data, when console.log the data i see it that's means it's working
this is code of api page
const { log } = console;
export default function teamAdd(req, res) {
if (req.method === "POST") {
const nftData = req.body;
log("Req payload", nftData);
res.json(nftData);
}
return res.status(500).json({
msg: "this needs to be post request",
});
}
and this is page where I try to fetch this store data from api. this is code , it's not working. I try so many time but it's always comes out with not data
function page() {
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(false);
const [comments, setComments] = useState([]);
const fetchComments = async () => {
const response = await fetch("/api/uploadNftData");
const data = await response.json();
setComments(data);
console.log(data);
};
useEffect(() => {
setLoading(true);
fetch("/api/uploadNftData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
setData(data);
setLoading(false);
})
.catch((error) => {});
}, []);
if (isLoading) return <p>Loading...</p>;
if (!data) return <p>No profile data</p>;
return (
<>
<Main>
<Templatepage>
<TemplateHeader />
<Herosec>
marketplace
<Box
sx={{
background: "#000",
height: "200px",
width: "200px",
margin: "80px",
}}
>
<h1 style={{ color: "#fff" }}>{data.addStory}</h1>
<p style={{ color: "#fff" }}>{data.selectedVideoUrl}</p>
</Box>
</Herosec>
</Templatepage>
</Main>
</>
);
}
What happens if you try to update the dependency array of the useEffect with data
useEffect(() => {
setLoading(true);
fetch("/api/uploadNftData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
setData(data);
setLoading(false);
})
.catch((error) => {});
}, [data]);
And I would change the default state of
const [data, setData] = useState(null);
to something more reliable like some custom interface or type.
You can try to verify if data is null in useEffect and then do the request.
It should look something like this:
useEffect(() => {
if(data === null){
setLoading(true);
fetch("/api/uploadNftData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
setData(data);
setLoading(false);
})
.catch((error) => {});
}
}, [data]);

seting auth token in react native not working

i am trying to set auth token in react native but it is not working.the api call to the url is woeking and data is saved to db but the token doesnot work
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(function (response) {
console.log('working');
ReactSession.setStoreType('Bearer', response.data.token);
ReactSession.set('username', 'Meon');
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
i get this error
console.log(response); returns the following
I use AsyncStorage together with fetch to set mine and then when i want to use it , I also call AsyncStorage from '#react-native-async-storage/async-storage';
After setting the state like this,
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
I try to simulate a Login
To login looks like this :
FunctionLogin = async () => {
let item = {email, password};
fetch('http://192.168.1.101/api/auth/sign-in', {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) => {
if (responseJson.message === 'OK') {
var token = responseJson.token;
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('token', token);
navigation.replace('Dashboard');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}
To use it in any page, I use it like this , later i reference the function in useEffect
showdata = async () => {
let token = await AsyncStorage.getItem('token');
alert(token);
};
Suppose I want to get transaction list from my endpoint to display data I do it like this
getTransactionsList = async () => {
let token = await AsyncStorage.getItem('token');
let email = await AsyncStorage.getItem('email');
var url = 'https://192.168.1.101/api/user-data/get-transactionby-email/';
fetch(url + email, {
method: 'GET',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`,
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
};
Then suppose i want to call it inside useEffect, I do like this
useEffect(() => {
getTransactionsList();
});
Thats what and how i do it and it works fine. If you also know how to use Redux, its still a good one as well.

How to pass the parameter to another screen using axios?

I'm doing the verification of the phone number, and I have to pass the phone number to the other checkCode.js component.
I have seen examples that pass it navigate() as a pramas, but how can I receive it in another component.
register.js
const SignUp = ({ navigation }) => {
const [phoneNumber, setPhoneNumber] = useState('');
let register = "https://app.herokuapp.com/api/v1/auth/register"
let sendVerification = "https://app.herokuapp.com/api/v1/auth/sendVerification-otp"
const signUp = () => {
const userParams = {
phone: phoneNumber,
};
const requestOne = axios.post(register, userParams)
const requestTwo = axios.post(sendVerification, userParams)
axios
.all([requestOne, requestTwo], userParams)
.then(axios.spread((...responses) => {
navigation.navigate('CodeVerification')
}))
.catch((err) => {
console.log('the error:', err.message);
})
}
checkCode.js
export default function CodeVerification({navigation}) {
//need phoneNumber param in this component
const [code, setCode] = useState('');
const confirm = () =>{
const userParams = {
phone: "+11111111",
code:code,
};
axios
.post('https://app.herokuapp.com/api/v1/auth/sendVerification-otp', userParams)
.then((response) =>{
console.log('response', response.data);
navigation.navigate('Welcome')
})
.catch((error) => {
console.log('the error:', error.message);
});
};
How can I pass it?
This might help
register.js
const SignUp = ({ navigation }) => {
// existing code remains the same
const signUp = () => {
....
axios
.all([requestOne, requestTwo], userParams)
.then(
axios.spread((...responses) => {
// send params like this
navigation.navigate("CodeVerification", {phone: phoneNumber});
})
)
.catch((err) => {
console.log("the error:", err.message);
});
};
};
checkCode.js
export default function CodeVerification({ route, navigation }) {
// get phoneNumber from props
const {phone} = route.params; // UPDATED this line
const [code, setCode] = useState("");
....
}
You can use Context Api
Context api is commonly used for transferring data to another component.

React Native fetch URL - passing hook value as parameters

What is the proper way to pass a useState hook value as a query parameter in a REACT NATIVE fetch url? The function returns that my jwt is malformed it's not reading the value of the hook properly. The two hooks are below, I'm trying to use those as query parameters in the fetch URL AND header authorization. $Are typically JQuery, but not sure the proper syntax for React Native - Expo.
const [user, setUser] = useState();
const [userID, setUserID] = useState();
const [subscriptions, setSubscriptions] = useState();
useEffect(() => {
const fetchSubUploads = async (userID, user) => {
const response = await fetch(
`content/subs/uploads/**${userID}**`,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer **${user}**`
},
});
let data = await response.json();
console.log(data);
setSubscriptions(data.subscriptionUploads);
return data;
};
const getUser = async() =>{
const loggedInUser = await AsyncStorage.getItem('fariToken');
if(!loggedInUser){
Alert.alert('Please Login')
}if(loggedInUser){
setUser(JSON.stringify(loggedInUser))
}
}
fetchSubUploads();
}, []);
I suggest spitting the useEffect in two. One effect is obviously dealing with making the fetch request with the appropriate data, user and userID, and so should have a dependency on these values, while the other effect deals with loading some "initial" state values from storage.
Example:
const [user, setUser] = useState();
const [userID, setUserID] = useState();
const [subscriptions, setSubscriptions] = useState();
useEffect(() => {
const getUser = async () => {
const loggedInUser = await AsyncStorage.getItem('fariToken');
if (loggedInUser) {
setUser(JSON.stringify(loggedInUser));
} else {
Alert.alert('Please Login');
}
}
getUser();
}, []);
useEffect(() => {
const fetchSubUploads = async (userID, user) => {
const response = await fetch(
`content/subs/uploads/**${userID}**`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer **${user}**`
},
}
);
const data = await response.json();
console.log(data);
setSubscriptions(data.subscriptionUploads);
return data;
};
if (user && userID) {
fetchSubUploads(userID, user);
}
}, [user, userID]);

Reset Select Item - React Native

I have a form which includes a select dropdown (items are populated via an api call). When I leave the screen I would like to be able to reset this back to it's initial state (Default state is a placeholder - Select Event)
I can clear text and textarea inputs within a useFocusEffect() but struggling with understanding how to reset a select dropdown
To reset the select dropdown i have tried setEventTypeData([]); but when navigating back to the screen, the last selected option is still selected (text inputs have been cleared though)
export const CreateNewEvent = ({navigation}) => {
const globalContext = useContext(AppContext);
const userId = globalContext.userInfo.id;
// dropdown populated with this
const [eventTypeData, setEventTypeData] = useState([]);
const [newEventDescription, setEventDescription] = useState('');
const [newEventLimit, setEventLimit] = useState(0);
const clearFormData = () => {
setEventTypeData([]); // tried setting back to original state but does not work
setEventDescription('');
setEventLimit(0);
};
useFocusEffect(
React.useCallback(() => {
const body = JSON.stringify({userId});
fetch(eventTypesUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: body,
})
.then(response => response.json())
.then(json => setEventTypeData(json))
.catch(error => console.error(error))
.finally(() => setLoading(false));
return () => {
// Run logic when the user leaves screen,
// Clear form
clearFormData();
};
}, [userId]),
);
// Select Dropdown
{/* Event Name Select Field */}
<FormControl isRequired isInvalid={'eventName' in errors}>
<FormControl.Label>Select Event</FormControl.Label>
<Select
onValueChange={newEventName =>
updateEventNameAndDescription(newEventName)
}
placeholder="Select Event"
{eventTypeData.map(event => (
<Select.Item
key={event.id}
label={event.name}
value={event.name}
/>
))}
</Select>
}
How can i ensure that when navigating back to this screen that the Select dropdown is reset to its original state
Thanks
I rewrite your example. I hope this help. You forget to unsubscribe
from API call
import { useIsFocused } from '#react-navigation/native';
const isFocused = useIsFocused();
useEffect(() => {
if (!isFocused) {
clearFormData()
}
}, [isFocused]);
useFocusEffect(
React.useCallback(() => {
const body = JSON.stringify({ userId });
const unsubscribe = fetch(eventTypesUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: body,
})
.then((response) => response.json())
.then((json) => setEventTypeData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
return () => unsubscribe();
};
}, [userId]),
);
export const CreateNewEvent = ({navigation}) => {
const globalContext = useContext(AppContext);
const userId = globalContext.userInfo.id;
// dropdown populated with this
const [eventTypeData, setEventTypeData] = useState([]);
const [newEventDescription, setEventDescription] = useState('');
const [newEventLimit, setEventLimit] = useState(0);
const [selectedEventName, setSelectedEventName] = useState();
const clearFormData = () => {
setSelectedEventName();
setEventDescription('');
setEventLimit(0);
};
useEffect(() => {
selectedEventName ? updateEventNameAndDescription(selectedEventName) : clearFormData();
}, [selectedEventName])
useFocusEffect(
React.useCallback(() => {
const body = JSON.stringify({userId});
fetch(eventTypesUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: body,
})
.then(response => response.json())
.then(json => setEventTypeData(json))
.catch(error => console.error(error))
.finally(() => setLoading(false));
return () => {
// Run logic when the user leaves screen,
// Clear form
clearFormData();
};
}, [userId]),
);
// Select Dropdown
{/* Event Name Select Field */}
<FormControl isRequired isInvalid={'eventName' in errors}>
<FormControl.Label>Select Event</FormControl.Label>
<Select
value={selectedEventName}
onValueChange={newEventName =>
setSelectedEventName(newEventName)
}
placeholder="Select Event"
{eventTypeData.map(event => (
<Select.Item
key={event.id}
label={event.name}
value={event.name}
/>
))}
</Select>
}
If you're using React Native Picker or something related, That picker is bound to the device native Select component, This has more performance benefit as it's not run on JavaScript thread, React rerendering will not affect that component.
But in this situation, we need to force this component to unmount when the user leaves the screen or mount when the screen is focused.
// Top-level import
import { useIsFocused } from '#react-navigation/native';
// Inside functional component
const isFocused = useIsFocused();
// Force <Select> to unmount or mount when screen focused
{ isFocused && <Select
value={selectedEventName}
onValueChange={newEventName =>
setSelectedEventName(newEventName)
}
placeholder="Select Event"
{eventTypeData.map(event => (
<Select.Item
key={event.id}
label={event.name}
value={event.name}
/>
))}
</Select>}