react-native-navigation get params in componentDidMount - react-native

i'm trying to list some products. i want to get categoryName as title by navigation, well if i put that line in render it works but i need to use it in componentDidMount how can i do that? is there any suggestions?
there is some part of my code
export default class ProductList extends React.Component {
navigation = this.props.navigation;
constructor(props) {
super(props);
this.state = {
isData: false,
};
}
componentDidMount() {
const title = navigation.route.params.categoryName; //here is my problem
fetch(global.apiPost + global.token, requestOptions)
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
if (element.Menu === title) {
products.push(element);
}
});
this.setState({isData: true});
})
.catch((error) => console.log('error', error));
}

put a check in componentDidMount
componentDidMount() {
if (navigation?.route?.params?.categoryName){
const title = navigation.route.params.categoryName; //here is my problem
fetch(global.apiPost + global.token, requestOptions)
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
if (element.Menu === title) {
products.push(element);
}
});
this.setState({isData: true});
})
.catch((error) => console.log('error', error));
}
}

Related

Fecth JSON URL in React Native

I am trying to obtain the data from this website: https://reactnative.dev/movies.json
I use the following code:
fetch("https://reactnative.dev/movies.json")
.then(response => response.json())
.then((responseJson) => {
setTimeout(() => {
this.setState({
loading: false,
dataSource: responseJson
})
}, 2000)
Alert.alert(responseJson)
})
.catch(error => console.log(error))
return (
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={this.onRefresh} tintColor={themes[theme].auxiliaryText} />
}
/>
);
};
My problem is that Alert.alert (responseJson) throws the following error:
This error
... and I would like to get the data for the flatlist.
Who helps me, please?
UPDATE:
...
constructor(props) {
super(props);
this.state = {
moviesList: '',
};
}
...
renderScroll = () => {
const { moviesList } = this.state;
fetch("https://reactnative.dev/movies.json")
.then(response => response.json())
.then((responseJson) => {
setTimeout(() => {
this.setState({
loading: false,
moviesList: responseJson.movies
})
Alert.alert(moviesList)
}, 2000)
})
.catch(error => console.log(error))
...
I would like Alert.alert to receive the data. That is to say, get the data out of the fetch function.
If inside the Alert.alert I put responseJson.movies if the data appears, but if I put moviesList it won't
If I post the following in the browser console it sends me an undefined error. I just want to receive the data from outside the function.
fetch("https://reactnative.dev/movies.json")
.then(response => response.json())
.then((responseJson) => {
setTimeout(() => {
this.setState({
loading: false,
moviesList: responseJson.movies
})
}, 2000)
})
.catch(error => console.log(error))
alert(this.moviesList)
You must print your response data by console.log and make sure what the response data is.
According to your error, I think you are getting Object type data after fetching, but you need to assign String into Alert.alert, therefore I suggest you try the following.
Alert.alert(responseJson.title)
I just tested this code it seems to be working. Is that what you are looking for?
with currElement you have access to the filmed object.
import { useEffect, useState } from "react"
function Home() {
const [isLoading, setLoading] = useState(true)
const [data, saveData] = useState([])
useEffect(() => {
fetch("https://reactnative.dev/movies.json")
.then(response => response.json())
.then(responseJson => {
console.log(responseJson.movies)
saveData(responseJson.movies)
setLoading(false)
})
.catch(error => console.log(error))
}, [])
console.log(data)
return isLoading ? (
<p> i am loading</p>
) : (
<ul>
{data.map(currElement => (
<li key={currElement.id}> {currElement.title}</li>
))}
</ul>
)
}

Getting variable from AsyncStorage and putting into Axios

I have been trying to get a variable from AsyncStorage and then put it into an Axios get request. The problem is that the variable is not updating to the data that is retrieved from AsyncStorage. How do I make it do that?
Here is my code:
const [sku, setSku] = useState('')
const STORAGE_KEY_SKU = '#save_sku'
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
alert('Failed to fetch the data from storage')
}
}
useEffect(() => {
readSku()
}, []);
useEffect(() => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${sku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
Im trying to put get the sku variable from the state from AsyncStorage, but the ${sku} in the axios get request link is not working, the sku is blank in that statement.
Please help, thanks!
useFocusEffect(() => {
readSku()
}, []);
const STORAGE_KEY_SKU = '#save_sku'
// to get the session username from localstorage
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
console.log(e);
}
}
const setSku = async (selectedSku) => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${selectedSku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}

Calling componentWillMount every time focused page in react native

I want call the componentWillMount every time that I focused a page. I using react-redux and react-navigation.
With react-navigation I use import { withNavigationFocus } from 'react-navigation'; to detect if the page was active but when I call componentDidMount there ara a few seconds that I see old view. Is for this I want calling componentWillMount instead of componentDidMount when page focused.
This is my code:
class HomeScreen extends React.Component {
componentWillMount() {
this.props._loading(true);
}
omponentDidMount() {
const { navigation } = this.props;
this.focusListener = navigation.addListener('didFocus', () => {
this.setState({loading: 0});
this.props._loading(true);
Api.get('s?type=Featured')
.then( response => {
if (response.profiles){
this.setState({featured_users: response.profiles, loading: this.state.loading + 1});
}
}).catch((error) => {
console.log(error);
this.props._loading(false);
});
Api.get('s?type=Top')
.then( response => {
if (response.profiles){
this.setState({featured_top: response.profiles, loading: this.state.loading + 1});
}
}).catch((error) => {
console.log(error);
this.props._loading(false);
});
});
}
componentWillUnmount() {
// Remove the event listener
this.focusListener.remove();
}
render() {
if (this.state.loading >= 4){
this.props._loading(false);
}
return (
...
);
}
}
const mapStateToProps = (state) => ({
user: state.reducerUser,
loading: state.reducerGeneral
});
mapDispatchToProps = dispatch => {
return {
_loading: loading => {
dispatch(actionLoading(loading));
},
updateUser: user => {
dispatch(actionUser(user));
},
}
}
export default withNavigationFocus(connect(mapStateToProps, mapDispatchToProps)(HomeScreen));
You can add this inside your componentWillMount and whatever you write inside your addListener , it will be executed everytime:
this.focusListener = this.props.navigation.addListener('didFocus', () => {
// The screen is focused
this.getData();
});

React Native, Fetch, and Dispatch: How do I access responseData within mapDispatchToProps()?

I'm fetching JSON Data within componentWillMount() from my "Scanner" component like so:
async componentWillMount() {
const url = 'https://foo.com/products/product1.json';
fetch(url)
.then((response) => response.json())
.then((responseData) => this.props.dispatchProductLoad())
.catch(error => {
console.log(error);
});
}
And below is my dispatch code:
function mapDispatchToProps(dispatch) {
return { dispatchProductLoad: () => dispatch(productLoad(SOMEDATA)) };
};
export default connect(null, mapDispatchToProps)(Scanner);
Where the variable SOMEDATA should hold the value from responseData (at the moment it's not defined)
So my question is - how do I set the value of SOMEDATA to the value held in responseData?
You would call the action creator with the responseData as an argument and define your mapDispatchToProps function like
async componentWillMount() {
const url = 'https://foo.com/products/product1.json';
fetch(url)
.then((response) => response.json())
.then((responseData) => this.props.dispatchProductLoad(responseData))
.catch(error => {
console.log(error);
});
}
function mapDispatchToProps(dispatch) {
return { dispatchProductLoad: (response) => dispatch(productLoad(response)) };
};
export default connect(null, mapDispatchToProps)(Scanner);

React Native app won't fetch api data

My React Native app won't fetch or get api data. It will not console log data or even an error. I've tried using fetch and axios.
fetch method:
export default class List extends React.Component {
commponentDidMount() {
fetch(URL)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
.catch(error => {
console.log(error);
});
}
}
axios method:
export default class List extends React.Component {
commponentDidMount() {
axios.get(URL)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
I'm not sure what the problem is and I can't find a solution online.
Please do check spelling function componentDidMount
And try below sample code I have.
componentDidMount() {
let URL = `https://...`;
fetch(URL)
.then(res => res.json())
.then(res => {
console.log('response:', res.data);
});
}
Hope it will help.