getInitialProps is not returning API's response - reactjs

I got this code:
import React from 'react'
import fetch from 'isomorphic-unfetch'
import Layout from '../../src/components/layout'
import Nav from '../../src/components/nav'
import Fluid from '../../src/components/fluid'
Post.getInitialProps = async ({ query }) => {
const res = await fetch(`https://schoolvol.mdcholewka.now.sh/api/getPost?slug=${query.slug}`)
const json = await res.json()
return json
}
function Post({ post }) {
return (
<Layout>
<Nav />
<Fluid>
{post ? <p>{post.id}</p> : <p>Ładowanie...</p>}
</Fluid>
</Layout>
)
}
export default Post
The problem is, when I load the site it returns "Ładowanie..." (which means loading in Polish). After a while, nobody happens. What's the solution?

I took a look at this sample: https://nextjs.org/learn/basics/fetching-data-for-pages/fetching-batman-shows. Instead of doing return json, I believe that you have to use return { post: json }.

Nevermind, I just remove these {} out of function's arguments and it's now working fine.

Related

Next.js getStaticProps not works in Header

Im trying to get some informations with api in my header. But not works. my codes.
export async function getStaticProps() {
console.log("test")
const res = await fetch(`https://api.namefake.com`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data },
}
}
I put console.log in function for to test whether the function is runs. but nothing shows up in console. I tried this in _app.js and It worked but I want to use in Header. Im using layout for pages.
layout :
import Header from './header'
export default function Layout({ children }) {
return(
<>
<Header/>
{children}
</>
);
}
_app.js
import Layout from './layout'
function MyApp({ Component, pageProps }) {
<Layout>
<Component {...pageProps} />
</Layout>
</>
);
}
export default MyApp
functions like getStaticProps() getServerSideProps() are server side functions and does not get passed to client side and so it works only in page components (pages/index.js ) and it does not in components which usually get passed to client bundle

How to import component to component in nextjs

I have created hello component, I fetched API data in hello component checked browser http://localhost:3000/hello working fine, I want import inside of index.js component now I checking http://localhost:3000/. but data not coming what issues. could you please solve this issue please below my code
hello.js:
function Hello({ posts }) {
console.log(posts)
return (
<>
<ul>
{posts.map((post) =>(
<p>{post.name}</p>
))}
</ul>
</>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries. See the "Technical details" section.
export async function getServerSideProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
export default Hello
index.js
import React from 'react';
// import Layout from "../components/layout";
// import NavBar from "../components/navbar";
import Hello from './hello'
function Index() {
return (
<>
<Hello />
</>
)
}
export default Index;
I am pretty sure that you can only use getServerSideProps in a page component, not in an embedded component. So the solution to this is to import it in index.js and then send the data down to hello.js through props.
EDIT:
here is the code -->
hello.js
function Hello(props) {
return (
<>
<ul>
{props.posts.map((post) =>(
<p>{post.name}</p>
))}
</ul>
</>
)
}
export default Hello
index.js
import React from 'react';
import Hello from './hello'
function Index({posts}) {
return (
<>
<Hello posts={posts}/>
</>
)
}
export async function getServerSideProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const posts = await res.json()
return {
props: {
posts
},
}
}
export default Index;

How to use axios to make requests in react

I started learning React about 3 or 4 months ago. Initially went through Codecademy's course, and have since polished up a lot with other courses and tutorials, the main of which used Axios for get requests without really explaining Axios. I decided to go back to the "Ravenous" yelp clone project at Codecademy, the instructions of which are for class components, and thought it would be a nice challenge to complete that same project but with functional components. Everything was perfect until it was time to wire up the Yelp api, and given my lack of knowledge with axios and requests in general, I can't pinpoint what I'm doing wrong. I'm almost certain that I'm doing something wrong in Yelp.js, but I can't be sure because I'm getting a type error that "fetchRestaurants" is not a function in App.js, no matter which way I call it. I think it involves Promises, and I tried using async/await on searchYelp, but this part is all new to me.
Here's Yelp.js:
import axios from "axios";
const KEY = "RwNYGeKdhbfM1bo6O8X04nLNR7sKjIXyAQ-Fo-nz-UdNHtSKDAmHZCc9MSiMAVmNhwKrfcukZ0qlHF1TdVIRSrgak3-oHVNmGD5JPR4ysxhfGd1hgOllt83H1i44X3Yx";
const fetchRestaurants = (term, location, sortBy) => { const corsApiUrl = "https://cors-anywhere.herokuapp.com/"; return () => {
axios
.get(
`${corsApiUrl}https://api.yelp.com/v3/businesses/search?categories=restaurants&location=${location}&term=${term}&sort_by=${sortBy}`,
{
headers: {
Authorization: `Bearer ${KEY}`,
},
}
)
.then(res => res.data.businesses)
.catch(error => console.log(error.response)); }; };
export default fetchRestaurants;
And here's App.js:
import React, { useState } from "react";
import BusinessList from "./BusinessList";
import SearchBar from "./SearchBar";
import Yelp from "./Yelp";
import "./App.css";
const App = props => {
const [businesses, setBusinesses] = useState([]);
const searchYelp = (term, location, sortBy) => {
const businessList = Yelp.fetchRestaurants(term, location, sortBy);
setBusinesses(businessList);
};
return (
<div className="App">
<h1>Ravenous</h1>
<SearchBar searchYelp={searchYelp} />
<BusinessList businesses={businesses} />
</div>
);
};
export default App;
Apologies in advance if this was supposed to be posted somewhere else. Noob probs.
you did not save the response anywhere. .then(res => res.data.businesses) here the response should've been saved somewhere, either a varibale or state. also your function responseble for the axios request doesn't return anything.
It's not an issue with axios itself, but how you use it in your React application.
Yelp.js: fetchRestaurants() should return a proper value (promise in this case) :
const fetchRestaurants = (term, location, sortBy) => {
return axios
.get(url, options)
.then(res => res.data.businesses)
.catch(...)
}
App.js: All API calls should be done using useEffect hook:
useEffect(() => {
Yelp.fetchRestaurants(term, location, sortBy)
.then(businessList => setBusinesses(businessList));
}, [term, location, sortBy]);

How to fetch Data on load component using React-Redux and Axios?

I have a need to fetch data from an API on component load, am using axios to fetch data, I need to save the response to the state and get back when the component load.
But i could do as am new to this.
My codes as below.
Sales.js : (This is where I fetch My components)
function SalesDesk() {
return (
<div>
<FoodScreen />
</div>
)}
export default SalesDesk;
FoodScreen.js (This is where i need to list my results to a variable, to map it later)
function FoodScreen() {
return(
<div className="sdFoodScreenMain">
{console.log(items)} // The results should be displayed here
</div>
)}
export default FoodScreen;
API.js (Here is where where i use my axios Router)
const API_URL = `https://jsonplaceholder.typicode.com/`; //Mock api for test purposes
export const GetAllItems = () => {
return (dispatch) => {
axios.get(API_URL)
.then(response => {
dispatch(allItemsList(response.data));
})
}
};
ItemsReducer.js (The reducer Logic)
const ItemsReducer =(state:Array = null, action) =>{
if (action.type === 'ALL_ITEMS') {
return GetAllItems ;
} else {
return state= null;
}
};
export default ItemsReducer
SalesAction.js (Action list)
export const allItemsList = () => {
return {
type: 'ALL_ITEMS'
};
};
All I need to do is fetch the the data from the API and display it in the console, when the component renders.so that I can display it in a map of div boxes for future purposes. Am new to both react and Redux, so ignore if any logic or implementation issues.
At first Router.js is a bad name(api.js etc), You should connect Sales.js to redux, using { connect } from 'react-redux'. See there https://redux.js.org/basics/usage-with-react and call action to fetch data in Sales.js
All I had to add an useDispatch on the component render, so it could fetch the data to the component on load.
import Reactfrom 'react'
import {useDispatch} from "react-redux";
import {GetAllItems} from 'API' //File containing the axios function
export function SalesDesk() {
const dispatch = useDispatch();
dispatch(GetAllItems())
return (
<div>
<FoodScreen />
</div>
)}
This helped me to fetch add add to state on component load.

Fetch data from GET request

When I call my API via my web browser I get the following result:
{"statusCode": 200, "body": "\"Cheers from AWS Lambda!\""}
However, I am now struggeling to show body via axios. Do you see what I am doing wrong?
import axios from "axios";
import React, { Component } from "react";
class App extends Component {
state = {
messages: []
};
componentDidMount() {
axios
.get(
"https://12345.execute-api.eu-central-1.amazonaws.com/prod/get-data"
)
.then(response => {
const messages = response.data;
this.setState({ messages });
});
}
render() {
return (
<ul>
{this.messages}
Test
{this.state.messages.map(message => (
<li>{message}</li>
))}
</ul>
);
}
}
export default App;
A few points:
1) Change this.messages in ul of render method to this.state.messages, as this.messages is undefined.
2) A good practice while using JSX is to keep js and html code as distinguishable as possible, so the map on a list should be done outside the return statement.
const listItems = numbers.map((number) =>
<li>{number}</li>
);
return (
<ul>{listItems}</ul>
);
3) For more info about CORS error and how to rectify it while using AWS lambda, refer to this article which includes a code snippet: AWS: CORS

Resources