Reputation: 834
I'm having trouble with NextJS rendering out my text from my API call. Basically, I make an external HTTP request to get some mock data. The mock data comes back in the form of props on the component via the getStaticProps method. In my JSX, I loop through the props via {props.data...}. I'll show the code below for brevity's sake.
import * as React from "react";
import { useState, useEffect, useCallback, memo } from "react";
import { GetStaticProps } from "next";
type Props = {
props: {
data: {}[];
};
};
const Form: React.NamedExoticComponent<
| React.RefAttributes<React.Component<{}, any, any>>
| { children?: React.ReactNode }
> = memo((props) => {
const [formData, setFormData] = useState({ username: "", password: "" });
const handleSubmit = (e) => {
e.preventDefault();
};
const handleSetFormData = useCallback(
(e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
},
[formData]
);
return (
<>
<form
onSubmit={handleSubmit}
style={{
display: "flex",
flexFlow: "column nowrap",
justifyContent: "center",
alignItems: "center",
height: "100vh",
}}
>
<input onChange={handleSetFormData} type="text" name="username" />
<input onChange={handleSetFormData} type="text" name="password" />
<button onSubmit={handleSubmit} type="submit">
Submit
</button>
</form>
{props.data.map((data) => {
return (
<ul key={data.id}>
<li style={{ color: "red", fontSize: "24px" }}>{data.completed}</li>
<li>{data.title}</li>
</ul>
);
})}
</>
);
});
type GetStaticPropsTypeInterface = {
props: {
data: {}[];
};
};
export const getStaticProps: (
props: React.PropsWithChildren<GetStaticPropsTypeInterface>
) => Promise<{ props: { data: any } }> = (props) => {
return fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((res) => {
return {
props: { data: res },
};
});
};
export default Form;
and the resulting HTML looks like this...
Upvotes: 1
Views: 1816
Reputation: 841
The code looks fine, so I guess that problem might be related to something else.
My feeling is that you probably placed your Form component into components
or src
directory. Next.js is looking only inside of a pages
directory and renders these pages on the server side.
Here's a dummy example - what is happening if you use this getStaticProps
function outside of pages
directory
https://codesandbox.io/s/strange-feather-odg7x?file=/pages/index.tsx
So the solution would be to fetch the data in pages/somePage.tsx
and forward props like this <Form data={props.data}...
Upvotes: 2