I build a simple django rest api now i need to fetch data from it in frontend using React Native.
I can make a request to the api but the data is not coming from there.
I search about it a lot but didn't find any help
Thanks in advance...
npm install axios
const axios = require('axios')
export const App = () =>{
const Your_Request = () =>{
const config= {
method:'get',
url:'YOUR URL',
}
axios(config).then((response)=>{
console.log('response',response)
}).catch((error)=>{
console.log('error',error)})
}
return (<View></View>)
}
You should first try to see whether your API works correctly.
I can recommend you Postman (https://www.postman.com/) for that.
It's free, comes with an intuitive GUI, and allows you to make requests to your API, see the returned data, status codes, headers, and so on.
Once the API returns the data correctly, you'll need to fetch the data in the React application. For that you can either place fetch() requests in the respective lifecycle methods, although this will get burdensome quite quickly if you need authentication, etc..
Another option would be to build service infrastructure using React hooks to share state (such as API tokens) across the component tree.
Here's a post I wrote on how to do that: https://schneider-lukas.com/blog/react-connect-rest-api.
Related
Hi i am having api routes which listens to incoming request ,
Code looks something like this
async function handler(req, res) {
// Run the middleware
await runMiddleware(req, res, cors)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
console.log(req.body)
}
export default handler
whenever this request comes in , how can i interact with this data and use these on pages?
If you need this data before the page is rendered then you would not use API routes. You can (and should) use all kinds of things directly inside getServerSideProps OR getStaticProps. This basically means that you could query your DB directly inside this functions. No need to go to the "server" to do that. It's a big context switch. Speaking of context, you can get url information and all sorts of things as argument to those functions mentioned above.
If you need this data after the page is rendered then you should use client-side fetch calls to get data. You can read up on that, it's basic react data fetching.
Relevant links
Context: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#context-parameter (for accessing stuff like params, query) before the page loads
React data fetching: https://www.robinwieruch.de/react-hooks-fetch-data/
I'm currently working on refactoring old code that uses the Stripe API.
I'm working with nextjs and the useStripe hook, however in the old code (in the backend), the:
const stripeApi = new Stripe(config);
instance was able to access methods such as:
stripeApi.customers.list(options)
Right now I am successfully calling the hook:
const stripe = useStripe();
It returns many usable methods but it does not allow me to access customers for example, am I initiating the instance in the wrong way, are they different instances?
useStripe is something from the client-side Stripe.js library, but things related to customers require the server-side stripe-node library.
I'm trying to learn react native by doing some practical. The problem I have is that I'm not able to use the images I stored in Firebase storage. O just don't know how to do it, so I hope you can help me.
I tried this from the official documentation, but is not working and is saying that await can only be used in async function.
import storage from '#react-native-firebase/storage';
const url = await storage()
.ref('images/profile-1.png')
.getDownloadURL();
If you run this code in a context where you can't use await, you can always use then() to accomplish the same:
storage()
.ref('images/profile-1.png')
.getDownloadURL().then((url) => {
console.log(url);
});
Just keep in mind that the url is only usable from inside the then callback or from code that you call from there. Trying to use url from elsewhere will result in it not existing, or not being initialized. To learn more about that, also see Why Does Firebase Lose Reference outside the once() Function?
I am getting a bit confused with the getServerSideProps of NextJS.
In the docs you can find this explanation.
For example, suppose that your page needs to pre-render frequently
updated data (fetched from an external API). You can write
getServerSideProps which fetches this data and passes it to Page
My confusing is why would you use getServerSideProps if you could simply fetch the data every x sec in your React component itself (after getting the initials data via getStaticProps).
Is there an advantage of using getServerSideProps over just the React way ?
so like this for example :
useEffect(() => {
const interval=setInterval(()=>{
const fetchdata = async () => {
const res = await fetch("url")
const data = await res.json()
setsongs(data)
}
fetchdata()
},15000)
return()=>clearInterval(interval)
}, [])
Due to the documentation, getServerSideProps fetches the API data on every request. So, there is a difference between requesting with a time interval ( like you mentioned in the react version), or using getServerSideProps.
Also, remember that getServerSideProps is implemented on the server-side and might be useful in cases that SEO is important. However, if the server goes down in the cases that you use getServerSideProps the whole page would not be served anymore.
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
Meanwhile, Fetching data on the client side (or the React way) is useful when SEO is not relevant, the page doesn’t need to be pre-rendered.
https://nextjs.org/docs/basic-features/data-fetching#fetching-data-on-the-client-side
In my opinion, it would be better if you use getServerSideProps when the displayed data is changing frequently and the user should see the most updated one, SEO is vital and a longer Time to first byte (TTFB) is acceptable.
There are useCases for all of them. You can use useEffect if SEO is not a concern and you want data to be updated in real-time.
You can use getServerSideProps when you want to have a better SEO ranking in your page.
Sure You can use getStaticProps which is way faster but know that getStaticProps is best used if your page contents don't change and stay the same like in a e-commerce website's product detail page.
I am building a React JS app with react-router v5.
I have already set up a 404 page and it works well.
As you can see, in the console I’m getting response code I just need to understand how to set a 404 header in the React component from this api response.
I looked up this question and everyone says you should set it from server response, but I did not figure it out, because I'm here now for your help.
Thank you
import React from "react";
const baseURL = "https://dog.ceo/api/breeds/image/";
const phpRoute = "giveme404"; //if you put here "random" will work
class NotFoundPage extends React.Component {
componentDidMount() {
fetch(baseURL + phpRoute)
.then(response => response.json())
.then(function(response) {
console.log(response);
});
}
render() {
return <div>404 Error, Page not found</div>;
}
}
export default NotFoundPage;
codesandbox link
Response From Server
Get response from server to React
Here's an example error handling strategy you can adopt on the frontend.
Some highlights:
I added some sample React routing with 404 page to which to redirect
when certain conditions occur.
I used the axios library, because I'm not sure if the built-in fetch
method in JS offers the same control as axios in terms of global
error handling. Logic for api access logic is in api.js file, there
you can see I added an error interceptor (more about interceptors here) which kicks off whenever
there's an unhandled http error and redirects to the not found page
only in case of 404 status code.
The trickies part is the history object. As you may know, React
router keeps internally its own history object which handles route change subscriptions and you can't create
your own one and expect React to detect changes from it. So you must
access this object instead, it's harder to do it outside of a React
component, though. All routed components like MyFeatureComp receive
automatically the history object as prop. In its componentDidMount I
store that value in a global variable so I have access to it in the
api logic, but you'll need to come up with better approach I think, it's just for demo purposes.
Outside of this sample, error boundaries are nifty mechanism to handle errors in your render functions (not event handlers) (for either class or functional components). In my experience, I've used them mostly with the render-as-you-fetch strategy to incorporate them with the error boundaries. With that approach the request is effectively made in the render function as opposed to any callbacks like componentDidMount. But this is probably not the standard yet and official support will come probably in next major version, React 17.
I hope that helps, let me know if you have questions. ;)