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

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);

Related

react native all Axios methods not working second

I try page isfocused work this method.this is working and go to getuserform method.But Axios
does not request again.I can't see any response or exception.I get old data again.
useEffect(() => {
dispatch(getUserForm(id))
}, [id, isFocused])
export const getUserForm = (userId) => {
return dispatch => {
axios.get(`${APIURL}/Form/${userId}`)
.then(response => {
dispatch({
type: 'GET_USER_FORM',
userForm: response.data,
})
})
.catch(err => console.error)
}
}

react-native-navigation get params in componentDidMount

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));
}
}

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));
}

How to assign value to global variable in fetch method in react native?

I am creating a react native app and I'm getting data from an API. I need to assign specific data into a global variable. That means my API return JSON data like {user_Id:"1' user_name:'abc' user_email:'abc#gmail.con'}. I need to assign user_Id into a global variable to access that in all of my screens.
This is what I tried;
componentDidMount() {
const arrFinal = [];
const {userDel} = this.state;
fetch('my API url')
.then(response => response.json())
.then(responseJson => {
// console.warn(responseJson);
arrFinal.push(responseJson);
arrFinal.map((item, index) => {
global.UserID = item.user_Id
})
.catch(error => {
console.error(error);
});
console.error(global.UserID)
}
But here nothing will print on console. How can I fix this problem?
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
componentDidMount() {
const arrFinal = [];
const {userDel} = this.state;
fetch('my API url')
.then(response => response.json())
.then(responseJson => {
// console.warn(responseJson);
arrFinal.push(responseJson);
arrFinal.map((item, index) => {
global.UserID = item.user_Id
console.error(global.UserID)
})
.catch(error => {
console.error(error);
});
// console.error(global.UserID)
}
or :
async componentDidMount() {
const arrFinal = [];
const { userDel } = this.state;
const response = await fetch('my API url');
const responseJson = await response.json();
// console.warn(responseJson);
arrFinal.push(responseJson);
arrFinal.map((item, index) => {
global.UserID = item.user_Id;
console.error(global.UserID);
});
console.error(global.UserID);
}

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.