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.
Related
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)
}
}
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));
}
}
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);
I was trying to use the Async Storage official react native API. The code in my react native looks like this:
export function get(key) {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(key, (err, val) => {
if (err) {
reject(err)
} else {
if (val === null) {
reject('key_not_found')
} else {
var parsedVal = JSON.parse(val)
console.log('got value from storage =>', parsedVal);
resolve(parsedVal)
}
}
})
});
}
I worked for a week without any problem, but recently it starts to give this error
The logger output from remote JS debugger looks like this
I didn't change any of the npm modules except that I installed moment.js using npm install --save moment Any idea what might be happening here?
UPDATE:
The places where I used this exported function are:
//This one is inside the same file so I just use get without module name
export function retrieveCredential() {
return new Promise(function(resolve, reject) {
get('credential')
.then((val) => {
resolve(val)
})
.catch((err) => {
console.log(err)
reject(err)
})
});
}
//this function is also exported
export function autoLogin() {
return new Promise(function(resolve, reject) {
LocalStorage.retrieveCredential()
.then((credential) => {
loginWithEmail (credential.email, credential.password, false)
.then(() => {
resolve()
})
.catch((err) => {
console.log(err)
reject(err)
})
})
.catch((err) => {
console.log(err)
reject(err)
})
});
}
//This is finally used in one of the component
Authentication.autoLogin()
.then(() => { ... })
.catch(() => { ... })
Project search for localstorage.getItem result:
I am trying to get some data from an API using Fetch without success. For some reason the request is failing and I am not able to render the data... as I am quite new to React and Fetch I am not sure where the error is. Is it something to do with the way I am requesting the API?
Thank you in advance
class App extends React.Component {
render() {
return <Data />
}
}
class Data extends React.Component {
constructor(props) {
super(props)
this.state = {
requestFailed: false,
}
}
componentDidMount() { // Executes after mouting
fetch('https://randomuser.me/api/')
.then(response => {
if (!request.ok) {
throw Error("Network request failed.")
}
return response
})
.then(d => d.json())
.then(d => {
this.setState({
data: d
})
}, () => {
this.setState({
requestFailed: true
})
})
}
render() {
if(this.state.requestFailed) return <p>Request failed.</p>
if(!this.state.data) return <p>Loading</p>
return (
<h1>{this.state.data.results[0].gender}</h1>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
CodePen
As mentioned on the GITHUB docs, you can implement the fetch like
fetch('https://randomuser.me/api/')
.then((response) => {
return response.json()
}).then((d) => {
console.log('parsed json', d)
this.setState({
data: d
});
}).catch(function(ex) {
console.log('parsing failed', ex)
this.setState({
requestFailed: true
})
})
CODEPEN
fetch method should be
fetch('your_url')
.then (
response => {
if (response.status !== 200) {
return 'Error. Status Code: ' + response.status
}
response.json().then(result => console.log(result)) // do sth with data
}
)
.catch(function(err) {
console.log('Opps Error', err)
})
I think your problem is with
.then(response => {
if (!request.ok) {
throw Error("Network request failed.")
}
return response
})
There's no request object that has the property ok. Maybe you mean to check response.ok ?
.then(response => {
if (!response.ok) {
throw Error("Network request failed.")
}
return response
})