I'm practicing NUXT and from tutorial its working well. mine fail when entering the NUXT middleware. the logic is if page is redirecting to other page it will enter middleware and fetch the result using axios.
middleware/search.js
import axios from 'axios';
export default function ({ params, store }) {
console.log(store)
return axios.get(`https://itunes.apple.com/search?term=~${params.id}&entity=album`)
.then((response) => {
console.log(response.data.results);
store.commit('add', response.data.results)
})
}
when entering here the store.commit('add'... will result
Cannot read property 'commit' of undefined
when I echo commit = undefined.
What I'm missing? I already tried this.$store.commit(...) still undefined.
VUEX
store/index.js
import Vuex from 'vuex'
const createStore = () => {
return new Vuex.Store({
state: {
albums: []
},
mutations: {
add (state, payload) {
state.albums = payload
}
}
})
}
export default createStore
I found a solution from the comments of the said tutorial but I want to share here if others struggle it too.
halt your development server ctrl+C
then restart the your dev server
npm run dev
then VUEX will be seen now in the middleware tnx
Restarting the Dev Server worked for me as well. It seems Vuex isn't reloaded when changes are made.
Run npm run dev and it should work.
Related
I'm trying to test my firebase functions in my React Native Expo app. Here's my initialization code:
import { connectFunctionsEmulator, getFunctions } from 'firebase/functions'
// ...Initialize app
export const fucntions = getFunctions()
connectFunctionsEmulator(fucntions, "localhost", 5001)
I then have code which maps functions in an object:
import { httpsCallable } from "firebase/functions";
import { fucntions } from "../../firebase";
export default {
helloFirebase: httpsCallable(fucntions, "helloFirebase")
}
And I call the function as follows:
functionsObj.helloFirebase({ myParam: "Hello!" })
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error.message)
})
But when I call the function I get the following, very small and unspecific error message in the console:
ERROR: internal
I'm guessing it's something to do with not being able to access localhost, but I still don't know how to fix the issue.
Any help would be appreciated, thanks!
FIXED: I found this article on this exact issue.
Make sure to run firebase serve --only functions -o ${YOUR_LOCAL_IP} once you've followed all the steps
I want to call an API in asyncData()
async asyncData({ $axios, params, store }) {
let itemUUID = params.item;
let item = await $axios.get("/item/" + itemUUID);
return {item};
}
Problem: Axios is still making the request on http://localhost:3000
if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed.
This also works if I use my store action & make the call by using this.$axios
I am using #nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js
Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?
Edit: I checked the request that was made on HMR and this was triggered in the client.js.
If I call my store inside the created() hook the request gets executed successfully.
My nuxt.config.js:
publicRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.EXPRESS_SERVER_URL,
}
},
I'm not sure what is the NODE_TLS_REJECT_UNAUTHORIZED=0 thing doing but your frontend configuration (Nuxt) is working well so far.
Sorry if I cannot help on the Express part.
Maybe try to setup HTTPS locally on Nuxt: How to run NUXT (npm run dev) with HTTPS in localhost?
TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.
On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.
I am using a plugin to initialize Axios - with the token from the store.
But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.
In my axios.js plugin I changed:
export default function({ app, error: nuxtError, store }) {
const token = const token = store.state.user.token;
app.$axios.setToken(token, "Bearer");
}
to;
export default function({ app, error: nuxtError, store }) {
const token = app.$cookies.get("access_token");
app.$axios.setToken(token, "Bearer");
}
Now the token is present & used for every request happening server-side.
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
}
I have a React/Electron application I'm working on in which I want to use data from my Redux store to initialize my Axios client. The use case is, for example, on first load of the app the user enters some information, like their username. This is pushed to the Redux store (and persisted in localStorage for future use), then used in the baseURL of the axios client for subsequent network requests.
The problem is, I can't get axios to work with react-redux and the connect() function. Axios' function exports seem to be hidden by the exported HOC, and any time I call one of its functions I get the following error:
TypeError: _Client2.default.get is not a function
My client looks something like this:
import axios from "axios";
import { connect } from "react-redux";
const Client = ({ init }) => {
return axios.create({
baseURL: `http://${init.ip}/api/${init.username}`
});
};
const mapStateToProps = state => {
return { init: state.init };
};
export default connect(
mapStateToProps,
{}
)(Client);
What am I doing wrong here?
Here in react-redux documentation https://react-redux.js.org/api/connect#connect-returns it says that The return of connect() is a wrapper function that takes your component and returns a wrapper component with the additional props it injects. So it returns react component that wraps react component. Your function returns axios client, it doesn't render anything.
I prefer to use action creators and make api calls there(Therefore I don't pass axios client or whatever). But if I decided to that I would initialize axios client inside reducer and keep in the store. And then pass it to clients as props.
const mapStateToProps = state => {
return { axios: state.axios };
};
On top of #Ozan's answer, In this case what you can do is create a main component, connect it with redux and dispatch an action on mount to initialize axios client.
You should initiate AXIOS client before you load App.js. I recommend you can use redux-axios as redux middleware and use action to call api.
https://github.com/svrcekmichal/redux-axios-middleware
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?