I'm trying to get SWR to work. Every example I have found doesn't seem to work when i apply it to my code. I'm not sure what i'm doing wrong the code appears to be the same, i'm sure something super simple that i just can't see.
I have a boilerplate next.js app.
my index.js has;
import useSWR from 'swr'
export default function Home({ isConnected }) {
const { data, error } = useSWR('/api/')
return() //jsx here
}
when i start the development server up it tells me http://localhost:3000 is where the development server can be viewed. when i debug and pause in the on the return line it tells me that data and error are undefined. when i go to http://localhost:3000/api/ i get well formed json back(firefox renders it as json).
You need a method to make the request, for you case, it could be like:
import useSWR from 'swr'
import axios from 'axios';
export default function Home({ isConnected }) {
const fetcher = async () => {
return await axios.get('http://mipage/some/');
};
const { data, error } = useSWR('/api/', fetcher)
return() //jsx here
}
Related
I am making a simple program with a backend in ASP.NET Core Web API, and a frontend in JS React. I have a SQL-database in my backend with a table called Events (Arrangementer in Norwegian). The events table has three columns: ID, name, and description.
I have opened and started the react-project. In my App.js (which is the only file I have edited since opening the project), I am trying to fetch some event data from my SQL-database. When I try to console.log() the json-response, nothing gets outputted to the console. I have tried using an ASYNC function, but that doesnt work either. My backend is up and running, and I have data inside of the tables, i can see that when i click the fetch-url.
Here is the App.js file:
import logo from './logo.svg';
import './App.css';
import {useEffect, useState} from 'react'
function App() {
useEffect(() => {
fetch("https://localhost:7031/api/Arrangements")
.then((res) => res.json())
.then((json) => {
console.log(json)
})
}, [])
return (
<div className="App">
<header className="App-header">
testing project
</header>
</div>
);
}
export default App;
The getter in the Swagger UI
I believe something is wrong with the endpoint. First thing that strikes me is that the url you are using starts with https:// but adresses localhost. I'm aware that's possible, but are you sure it's not http:// ?
To be sure of that, please test your endpoint using Postman or the Chrome Dev tools network tab - both should give you sufficient information about the status of your endpoint.
Your frontend code looks good and should work, so I believe you have a backend problem.
Try it plz. Seems your code is fine. If your get response from Backhand(200 in Network Tab) no issues.
import React from 'react';
import { useState,useEffect } from 'react';
const MyApp = () => {
const [service, setService] = useState({})/According to Your API response;
useEffect(() => {
const url = "http://localhost:7031/api/Arrangements";
fetch(url)
.then(res =>res.json())
.then(data => setService(data));
}, [])
return (
<div>
<p>{service.length}</p>
</div>
);
};
export default MyApp;
If you console log the res, you will see some response.
But I don't think you can use JSON in the last .then, because res.json() doesn't save your data anywhere.
Try using a useState, and set that state in the last .then.
My error occurs when I try to send api requests with axios but do not see the same error sending the request with fetch. I looked at several react-native applications and It looks like I am using the axios.get method similar to theirs and don't see what I am doing wrong. I am new to react native so maybe I am doing something naively.
import React from 'react'
import {
View,
Button
} from 'react-native'
import axios from 'axios'
const Example = () => {
const requestGoogle = () => {
const url = 'https://google.com'
axios.get(url) //fetch(url) no error
.then(res => {
alert(res)
})
.catch(err => {
alert(err)
})
}
return ( <
View >
<
Button title = "Send"
onPress = {
() => requestGoogle()
}
/> <
/View>
);
}
export default Example
I get the following error when running the previous code:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
Looking into each reason:
I confirmed that React and React Dom have same react version 16.13.1
I don't think I but maybe?
I confirmed that only one copy of app exists in the project following their steps
on IndexPage i am calling an api using getStaticProps. when i console.log this on frontend i get an empty object on the browser.
iam using NextJS
const IndexPage = (props) => {
console.log(props)
return(
<h1>Hello</h1>
)
}
export async function getStaticProps() {
const res = await fetch("https://jsonplaceholder.typicode.com/todos");
const posts = await res.json();
return {
props: {
posts,
},
};
}
export default IndexPage;
Did not play around with it, but I'm almost sure that if you view console output of you console where you started nextjs app you will see results there, take a look please. Here is explanation from documentation:
If you export an async function called getStaticProps from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.
The key part here will pre-render at build time. So getStaticProps will be called on the server side during server side rendering.
I want to split my vuex file into modules, but as soon as I do that the promise I return from my action becomes undefined when I console log it in the actual template.
So in my action I have something like
return axios.get(....)
And in my component I have a method that does the following
this.$store.dispatch('setRules').then(response => {console.log(response)})
As soon as I switch from using store.js to importing a module in my store.js file, the response becomes undefined but the rest of vuex still works correctly. When checking the state I also see that the action actually gets executed and the state gets updated, so it seems as if it is a problem with axios.
The new store.js file looks the following:
import Vue from 'vue'
import Vuex from 'vuex'
import stock from './modules/stock';
Vue.use(Vuex);
export default new Vuex.Store( {
modules: {
stock,
}
});
And in my module stock.js I have something like this.
const getters = {..}
const actions = {..}
const mutations = {..}
const state = {..}
export default {
namespaced: false,
state,
mutations,
actions,
getters
}
Does anyone have an idea what I am doing wrong?
The above scenerio is happening because javascript is asyncronous and hence before the response from your api call is returned the console statement is executed and hence you see that as undefined.
You can try using async await on axios call as
async actionName ()
{
await axios.get(..).then(response => { console.log(response)} )
}
So I found out that the problem was caused by the fact that I tried to acces this.$store.state.x while it should be this.$store.state.stock.x. Is there a way to not need the module name to access the state?
I defined the following actions in ../actions/AuthActions.js:
export const emailChanged = (text) => {..};
export const passwordChanged = (text) => {..};
and exported them in "./index.js" as
export * from './AuthActions';
Imported the actions in LoginForm.js with
import { passwordChanged, emailChanged } from '../actions';
and used the actions in the following way:
onEmailChange(text) {
this.props.emailChanged(text);
}
onPasswordChange(text) {
this.props.passwordChanged(text);
}
On running the code in the emulator, I get the error 'undefined is not a function...', even though I have defined the function, exported the name. One of the exported names 'emailChanged' works as expected but only that one and as far as I can see there is nothing special about that name. I know I must be missing something glaringly obvious, but would appreciate any help.
I assume you are using redux, and trying to call actions from your component. The problem is that you did not connect your action creators with to component with redux's connect Higher Order Component.
What you need to do, is add these actions with connect like this:
import { connect } from 'react-redux';
export default connect(mapStateToProps, { emailChanged, passwordChanged })(LoginScreen)
This way, those actions will be available in this.props.