react query with parameters - react-native

I have a react query that wraps on of my API calls. I would like to expose a paramter to the user of my custom hook which lets them set the paramter for this specific API call.
How can I do that idiomatically?
My current custom hook looks like this:
const useGamesApi = () => {
const [games, setGames] = useState<Game[]>([]);
const upcomingGamesQuery = useQuery(
["upcoming", date],
async ({ queryKey }) => {
const [_, date] = queryKey;
const ret = await apiGetUpcomingGames(date);
return ret;
},
{
onSuccess: (data) => {
setGames(data);
},
}
);
return {
games: games,
};
};
export default useGamesApi;
This doesn't expose the date parameter as I would want it, since there is no external way of modifyin that date parameter.

You can just pass the parameter in braces, just like functions. Then user would be able to use it like useGamesApi(key)

Related

Spy on window function with testcafe

I want to test with testcafe if a function on a window object is executed with certain parameters. Is it possible with Testcafe?
The function call looks like this:
window.myObject.myFunction({customObject: true});
You can use the ClientFunction API to create a spy function in a window object. Please look at the following test example:
import { ClientFunction } from 'testcafe';
fixture `New Fixture`
.page `https://cf51n.csb.app/`;
const spyOn = ClientFunction(() => {
// Create an array where we store information about `myFunction` calls
window.myFunctionSpyData = [];
// Store the original `myFunction` value
window.orirginalFunction = window.myObject.myFunction;
window.myObject.myFunction = function() {
// Save data about the current call
window.myFunctionSpyData.push(...arguments);
// Call the original `myFunction` value
window.orirginalFunction(...arguments);
}
});
const getSpyData = ClientFunction(() => {
// Retrieve data about myFunction calls from client
return window.myFunctionSpyData;
});
const spyOff = ClientFunction(() => {
// Restore the original myFunction value
window.myObject.myFunction = window.orirginalFunction;
delete window.spyData;
});
test('New Test', async t => {
await spyOn();
await t.click('#btn');
const data = await getSpyData();
await spyOff();
await t
.expect(data.length).eql(2)
.expect(data[0]).eql('1')
.expect(data[1]).eql('2');
});

can't get data from server to NuxtJS Store

this is my code :
export const state = () => ({
products: []
});
export const getters = {
getProducts: state => {
return state.products;
}
};
export const mutations = {
SET_IP: (state, payload) => {
state.products = payload;
}
};
export const actions = () => ({
async getIP({ commit }) {
const ip = await this.$axios.$get("http://localhost:8080/products");
commit("SET_IP", ip);
}
});
the server is working nicely but i just can't get the data into the store
First of all, I highly recommend you rename your action and mutation to something like getProducts and SET_PRODUCTS instead of ip. Also make sure you change the variable name inside the action. While this doesn't change any functionality, it makes your code easier to read.
Second, maybe add a console.log(ip) right after you define the const in the action and see if you're getting the data you want in there. In most cases you're going to want to assign ip.data to your variable.
Lastly, make sure you're calling the action somewhere in the code.
You should do it like this:
this.$store.dispatch('getIP'); // Using your current name
this.$store.dispatch('getProducts'); // Using my recommended name

How to use debounce with Vuex?

I am trying to debounce a method within a Vuex action that requires an external API.
// Vuex action:
async load ({ state, commit, dispatch }) {
const params = {
period: state.option.period,
from: state.option.from,
to: state.option.to
}
commit('SET_EVENTS_LOADING', true)
const res = loadDebounced.bind(this)
const data = await res(params)
console.log(data)
commit('SET_EVENTS', data.collection)
commit('SET_PAGINATION', data.pagination)
commit('SET_EVENTS_LOADING', false)
return data
}
// Debounced method
const loadDebounced = () => {
return debounce(async (params) => {
const { data } = await this.$axios.get('events', { params })
return data
}, 3000)
}
The output of the log is:
[Function] {
cancel: [Function]
}
It is not actually executing the debounced function, but returning to me another function.
I would like to present a custom debounce method which you can use in your vuex store as
let ongoingRequest = undefined;
const loadDebounced = () => {
clearTimeout(ongoingRequest);
ongoingRequest = setTimeout(_ => {
axios.get(<<your URL>>).then(({ data }) => data);
}, 3000);
}
This method first ensures to cancel any ongoing setTimeout in the pipeline and then executes it again.
This can be seen in action HERE

redux-thunk: actions are not dispatching

I am trying to build an app in react native that is suppose to take take two inputs by a user and then make a query to an api and get information about the two inputs. I have been having trouble with redux and redux-thunk and specifically with async actions.
This is the code in my app that i am specifically having trouble with
export const fetchData = url => {
console.log("start Fetching");
return async dispatch => { // this is where the problem is
dispatch(fetchingRequest());
try {
const response = await fetch("https://randomuser.me/api/?results=10");
const json = await response.text();
if (response.ok) {
dispatch(fetchingSuccess(json));
console.log("JSON", json);
} else {
console.log("fetch did not resolve");
}
} catch (error) {
dispatch(fetchingFailure(error));
}
};
console.log("Fetched data");
};
Upon debugging the function, I have ended with finding that when the fetchData function is called the function will execute but the async dispatch that is being returned has undefined behavior.
The output in the debugger when the function is called should be
start Fetching
JSON file information/Error
but the output in the debugger is actually
start Fetching
This is the function in which fetchData is called in
_onPress = () => {
let url = "https://randomuser.me/api/?results=10";
fetchData(url);
console.log("should have fetched");
};
this is the mapDispatchToProps function that I have added. The problem is i do not know what to add inside the function.
const mapStatetoDispatch = (url, dispatch) => {
return {dispatch(fetchData(url))}; // do not know what to place in body of function
};
i have connected it in the component with
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
these are the action creators that I import, if needed
import {
fetchingSuccess,
fetchingRequest,
fetchingFailure,
fetchData
} from "../data/redux/actions/appActions.js";
Assuming you have added redux-thunk as a middleware, it looks like the errors are here:
_onPress = () => {
const { fetchData } = this.props;
let url = "https://randomuser.me/api/?results=10";
fetchData(url);
console.log("should have fetched");
};
and
const mapStatetoDispatch = dispatch => ({
fetchData: url => dispatch(fetchData(url)),
}};

Why is the parameter inside the action coming back as undefined when using redux?

Currently, I have a page which renders a list of dates, When a user presses a certain date, the user is then taken to a new page which renders the graph of the date that they pressed.
I want to use redux to update props, so that I can render a specific graph based on which button a user has pressed.
Inside my renderList() I return a mapped array that in turn returns a bunch of TouchableOpacities. Inside each TouchableOpacity, inside the onPress event, another function is called that passes all of the information about the test as a parameter. renderList looks like this.
let sorted = _.orderBy(this.props.testResults, testResult => testResult.created, 'desc');
moment.locale(localeToMomentLocale(I18n.locale));
return sorted.map((result, index) => {
let formattedDate = moment(result.created).format(I18n.t('report_header_dformat'));
let correctedDate = vsprintf(I18n.t('report_date_correction'), [formattedDate]);
let analysis = TestAnalysis.run(result);
return (
<TouchableOpacity
onPress={() => this.resultOrTest(result)}
style={styles.row} key={'_' + index}>
</TouchableOpacity>
resultOrTest looks like this:
resultOrTest = (result) => {
console.log('ReportDetailPage: resultOrTest: showing result: ', result.id);
this.props.setResultIdToProps(result.id);
this.props.navigation.navigate('ReportSinglePage');
};
mapDispatchToProps looks like this:
const mapDispatchToProps = (dispatch) => {
return {
setResultIdToProps: () => {
dispatch(setResultIdToProps());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ReportDetailPage);
inside my actions/user.js page.
export const setResultIdToProps = (resultId) => {
// var newId = resultId.toString();
console.log('actions/user.js setResultIdToProps: resultid.......', resultId);
return (dispatch, getState) => {
dispatch({
type: SET_RESULT_ID_TO_PROPS,
resultId
});
}
};
Why does resultId keep coming back as undefined? Did I pass the wrong value/Parameter?
You need to properly pass the parameter to your action dispatcher in mapDispatchToProps. Right now, you're not passing the resultId, hence it is passed as undefined.
const mapDispatchToProps = (dispatch) => {
return {
setResultIdToProps: (resultId) => {
dispatch(setResultIdToProps(resultId));
}
}
}