Dynamic axios request url in Vue 3 Composables - laravel

I've tried this and it worked:
const posts = ref{[]}
const urlEndPoint = 'posts'
const getPosts = async () => {
let response = await axios.get('/api/'+urlEndPoint)
posts.value = response.data.data
}
but that one is not dynamic. My goal is to make the urlEndPoint value reactive and set from the components
then i tried this:
const urlEndPoint = ref([])
but I don't know how to send the value of urlEndPoint constant back from the component to the composables.
I tried these in my component:
const urlEndPoint = 'posts'
and
const sendUrlEndPoint = () => {
urlEndPoint = 'posts'
}
but none worked.
is there a way to accomplish this goal? like sending the component name to urlEndPoint value in composable or any other simple way.

Define a composable function named use useFetch :
import {ref} from 'vue'
export default useFetch(){
const data=ref([])
const getData = async (urlEndPoint) => {
let response = await axios.get('/api/'+urlEndPoint)
data.value = response.data.data
}
return {
getData,data
}
in your component import the function and use it like :
const urlEndPoint=ref('posts')
const {getData:getPosts, data:posts}=useFetch()
getPosts(urlEndPoint.value)

Related

Sending multiple .get() requests with Storyblok-nuxt

Can someone please guide me regarding sending multiple .get() requests with Storyblok-nuxt?
I'm trying to do something like this:
context.app.$storyapi.all([requestOne, requestTwo]).then(
context.app.$storyapi.spread((...responses) => {
const responseOne = responses[0];
const responseTwo = responses[1];
console.log(responseOne, responseTwo, responesThree);
}));
Thanks.
Since the JS client of Storyblok is using an axios wrapper you can do it like this:
import axios from 'axios';
const requestOne = context.app.$storyapi.get('cdn/stories' + 'health', { version: "published" })
const requestTwo = context.app.$storyapi.get('cdn/datasources', { version: "published" })
const requestThree = context.app.$storyapi.get('cdn/stories' + 'vue', { version: "published" })
axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((...responses) => {
const responseOne = responses[0]
const responseTwo = responses[1]
const responesThree = responses[2]
// use/access the results
})).catch(errors => {
// react on errors.
})
Here is also a full tutorial on this: https://www.storyblok.com/tp/how-to-send-multiple-requests-using-axios

Multiple effects in functional component fails with server status code 500

This code, containing two effects, returns no data. However, when commenting out either one, data is returned normally.
When both effects are run, dev-tools network view shows vehicleList request headers 'Provisional' and vendorList with a status code of `500 Internal Server Error'.
Is it possible to request two effects in the same functional component? If yes, how?
PowMaintenance.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { PowForm } from './PowForm';
const server = `http://${process.env.REACT_APP_API_BACK_END_ADDRESS}:${
process.env.REACT_APP_API_BACK_END_PORT
}`;
const PowMaintenance = () => {
const [vehicleList, setVehicleList] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(`${server}/api/vehicle/VehicleList`);
setVehicleList(result.data);
};
fetchData();
}, []);
const [vendorList, setVendorList] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(`${server}/api/vendor/VendorList`);
setVendorList(result.data);
};
fetchData();
}, []);
console.log('vehicle', vehicleList);
console.log('vendor', vendorList);
return (
<div>
<PowForm vendorList={vendorList} onChange={onChange} />
</div>
);
};
export { PowMaintenance };
```
Yozi, thank you for your help. You were correct, it was in the API. I researched it only because of your insistence.
A programming error in TDS/MSSQL involving connections.

Selector for React-Redux

To use selector, I tried to follow this URL reference: https://blog.isquaredsoftware.com/2017/12/idiomatic-redux-using-reselect-selectors/
One of the example is :
const selectSomeData = state => state.someData;
const selectFilteredSortedTransformedData = createSelector(
selectSomeData,
(someData) => {
const filteredData = expensiveFiltering(someData);
const sortedData = expensiveSorting(filteredData);
const transformedData = expensiveTransformation(sortedData);
return transformedData;
}
)
const mapState = (state) => {
const transformedData = selectFilteredSortedTransformedData(state);
return {
data: transformedData
};
}
Question: Within mapState we are calling selectFilteredSortedTransformedData and we are also passing State as parameter. However, the function itself is not taking any parameter, how does it work?
const selectFilteredSortedTransformedData = createSelector(
did you add mapState function in redux connect function ?? something like this.
export default connect(mapState)(Component)

Example with redux-observable and redux-form for react-redux-promise-listener

React-redux-promise-listener contains only example for usage with React Final Form.
What is the right way to use it with redux-forms and redux-observable?
I had some success with using it with redux-observable. Have you seen the setup linked. Helped me when I was working on doing something similar:
// createStore.js
...
import createReduxPromiseListener from 'redux-promise-listener';
const reduxPromiseListener = createReduxPromiseListener();
function createStoreWrapper(history, testMiddleware) {
const middleware = [
createRouterMiddleware(history),
createEpicMiddleware(rootEpic),
createRavenMiddleware(Raven, {
// Optionally pass some options here.
}),
reduxPromiseListener.middleware,
];
if (testMiddleware) middleware.push(testMiddleware);
const enhancers = [responsiveStoreEnhancer, applyMiddleware(...middleware)];
if (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined') {
enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__());
}
const initialState = getInitialState();
const enhancer = compose(...enhancers);
const store = createStore(rootReducer, initialState, enhancer);
addHandlers(store);
return store;
}
Also see my somewhat-related question stack post.

Redux action ajax result not dispatched to reducer

I just get to experiment with Redux and I know that middleware is essential to make ajax calls. I've installed redux-thunk and axios package separately and tried to hook my result as a state and render the ajax result to my component. However my browser console displays an error and my reducer couldn't grab the payload.
The error:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
This is part of my code and how the middleware is hooked up:
//after imports
const logger = createLogger({
level: 'info',
collapsed: true,
});
const router = routerMiddleware(hashHistory);
const enhancer = compose(
applyMiddleware(thunk, router, logger),
DevTools.instrument(),
persistState(
window.location.href.match(
/[?&]debug_session=([^&]+)\b/
)
)
// store config here...
my action:
import axios from 'axios';
export const SAVE_SETTINGS = 'SAVE_SETTINGS';
const url = 'https://hidden.map.geturl/?with=params';
const request = axios.get(url);
export function saveSettings(form = {inputFrom: null, inputTo: null}) {
return (dispatch) => {
dispatch(request
.then((response) => {
const alternatives = response.data.alternatives;
var routes = [];
for (const alt of alternatives) {
const routeName = alt.response.routeName;
const r = alt.response.results;
var totalTime = 0;
var totalDistance = 0;
var hasToll = false;
// I have some logic to loop through r and reduce to 3 variables
routes.push({
totalTime: totalTime / 60,
totalDistance: totalDistance / 1000,
hasToll: hasToll
});
}
dispatch({
type: SAVE_SETTINGS,
payload: { form: form, routes: routes }
});
})
);
}
}
reducer:
import { SAVE_SETTINGS } from '../actions/configure';
const initialState = { form: {configured: false, inputFrom: null, inputTo: null}, routes: [] };
export default function configure(state = initialState, action) {
switch (action.type) {
case SAVE_SETTINGS:
return state;
default:
return state;
}
}
you can see the state routes has size of 0 but the action payload has array of 3.
Really appreciate any help, thanks.
It looks like you have an unnecessary dispatch in your action, and your request doesn't look to be instantiated in the correct place. I believe your action should be:
export function saveSettings(form = { inputFrom: null, inputTo: null }) {
return (dispatch) => {
axios.get(url).then((response) => {
...
dispatch({
type: SAVE_SETTINGS,
payload: { form: form, routes: routes }
});
});
};
}

Resources