Next.js Discord

Discord Forum

How to fetch data into client component

Answered
Atlantic herring posted this in #help-forum
Open in Discord
Atlantic herringOP
nothing is working tried axios,swr.
can someone tell me how to fetch data,
my file structure is like this
app/pages
app/components

i want to fetch the data in the components folder so i can use the components in the pages
Answered by joulev
try rendering this inside _app
View full answer

45 Replies

Atlantic herringOP
@joulev
and the output is blank
are you sure this is a client component
Atlantic herringOP
and the api is working fine i can see the json
are you sure this is a client component? i dont see a "use client" here
Atlantic herringOP
if you are sure it is a client component, maybe add some console.log?
.then((response) => {
  console.log(response);
  setAddresses(response.data);
})
Atlantic herringOP
still same output tho
you're right i did some changes and forgot to put it back
the thing is
when i log something i dont see it
i have 0 idea why
useEffect(() => {
  console.log("hello world")
  axios
    .get('http://localhost:1337/api/adresses')
    .then(...)
}, []);

does the hello world show up in browser console?
Atlantic herringOP
are you sure you used this component?
im fairly sure you forgot to render this component or something
Atlantic herringOP
dont render this inside _document
try rendering this inside _app
Answer
if you want it to show up in all pages
Atlantic herringOP
@Atlantic herring Click to see attachment
now if you open browser console the hello world should show up
this error means whatever response.data is, it is not an array so can't be map'd over
console.log(response.data) to see what it is
Atlantic herringOP
yes i can see hello world and hi
{data: Array(3), meta: {…}}
data
:
(3) [{…}, {…}, {…}]
meta
:
{pagination: {…}}
[[Prototype]]
:
Object
Atlantic herringOP
response . data
            .get('http://localhost:1337/api/adresses')
            .then((response) => {
                console.log(response.data);
                setAddresses(response.data);
            })
{data: {…}, status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …}
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
data
: 
{data: Array(3), meta: {…}}
headers
: 
AxiosHeaders {content-length: '1043', content-type: 'application/json; charset=utf-8'}
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
: 
200
statusText
: 
"OK"
[[Prototype]]
: 
Object
then it looks like you have to setAddress(response.data.data)
Atlantic herringOP
fuck ye
it works now
tx alot
ive been trying for 3 days
:noice:
Nice