does redux-query-sync enable sharing url between machines? - redux

I am trying to implement redux-query-sync but the url keeps going to default state if I share the url which has the updated state.
https://github.com/Treora/redux-query-sync/blob/master/src/redux-query-sync.js
I have implemented as shown in the sample - https://codesandbox.io/s/url-query-sync-qjt5f?from-embed=&file=/src/index.js
There is also a PropsRoute implementation in the code.

Your example seems to be working for the string arguments. It's the array param selected which is giving you trouble.
The action creator that you are dispatching here, changeLocation, does not take the right arguments. Look at how you are calling it in your component:
changeLocation({
location: event.target.name,
checked: event.target.checked
});
When it is called from the URL query it is going to be called like:
changeLocation([Stockholm, Oslo]);
So obviously these do not match up. The existing changeLocation action can only handle one location at a time, so there's not a way to map the value from the URL to a payload that you can use with it. You will need to create a separate action.
const setLocation = (payload) => ({ type: "setLocation", payload });
case "setLocation":
return {...state, selected: payload};
My first approach to handle the array values was to implement the optional stringToValue and valueToString settings for the selected param.
This only kinda-sorta works. I can't get it to omit the param from the URL when it is set to the default value. I wonder if it's using a === check? As a hacky solution, I added a filter in the stringToValue to prevent the empty string from getting added to the locations array. But the selected= is always present in the URL.
selected: {
selector: (state) => state.selected,
action: setLocation,
stringToValue: (string) => string.split(",").filter(s => !!s),
valueToString: (value) => value.join(","),
defaultValue: []
}
This really annoyed me, so I followed this bit of advice from the docs:
Note you could equally well put the conversion to and from the string in the selector and action creator, respectively. The defaultValue should then of course be a string too.
And this approach worked much better.
selected: {
selector: (state) => state.selected.join(","),
action: (string) => setLocation(string.split(",")),
defaultValue: ""
}
With those changes you should have a shareable URL.
Forked Sandbox

Thanks Linda. The example I sent was what I referred to do my implementation. It wasn't my work.
Just letting you know that since my app uses PropsRoute I was able to use history props to push the state as params in url and share the url. I had to modify code to use params from url as state if it was available. This worked between tabs. Will be testing across machines.
this.props.history.push("/currenturl/" + state)
this.props.history.push("/currenturl/" + {testobject:{}})
this.props.match.params.testobject
wasn't able to implement redux-query-sync though.

Related

How to extract params from received link in react native firebase dynamiclink?

I tried to migrate from react navigation deeplinks to firebase dynamic linking using this library (react-native-firebase).
I have set up everthing and links are being generated and received on the app. However, is there any way to extract the params sent in the link properly using this library?. Currenty this is my code for handling received link:
handleDynamicLink = () => {
firebase
.links()
.getInitialLink()
.then((url) => {
console.tron.log('link is ', url);
})
.catch((error) => {
console.tron.log(error);
});
};
The url received is
https://links.dev.customdomain.in/?link=products%2F1122
I want to extract the product id 1122 from the url. The only way for me right now is to parse the string and manually extract the relevant params. Unlike in react navigation deeplinks where I used to specify the path, like
Product: {
screen: Product,
path: 'customdomain/products/:slug',
},
Where the slug or id data used to pass as navigation param in the respective screen. Am I missing something? How can I pass mutliple params this way?
Point 2 in this link here says:
The response contains the URL string only.
This means that the firebase.links().getInitialLink() method does not return query parameters, at least as at the time of writing this (v5.5.5). To add your paramaters, you should use a URL with your query param as part of the URL. What I mean is this
Use https://links.dev.customdomain.in/link/products/1122
and use Regex to extract the product id which is of interest to you. This is what works for me and I hope it helps.

How to implement redux-search

I am trying to implement a search filter in my application which uses react/redux using redux-search. The first gotcha I get is when I try to add the store enhancer as in the example.
// Compose :reduxSearch with other store enhancers
const enhancer = compose(
applyMiddleware(...yourMiddleware),
reduxSearch({
// Configure redux-search by telling it which resources to index for searching
resourceIndexes: {
// In this example Books will be searchable by :title and :author
books: ['author', 'title']
},
// This selector is responsible for returning each collection of searchable resources
resourceSelector: (resourceName, state) => {
// In our example, all resources are stored in the state under a :resources Map
// For example "books" are stored under state.resources.books
return state.resources.get(resourceName)
}
})
)
I understand evarything up to the resourceSelector, when I tried to get a deep dive into the example to see how it works but I can barely see how they are generated and the last line returns an error, Cannot read property 'get' of undefined
My state object looks like this
state: {
//books is an array of objects...each object represents a book
books:[
//a book has these properties
{name, id, author, datePublished}
]
}
Any help from anyone who understands redux-search is helpful
If this line:
return state.resources.get(resourceName)
Is causing this error:
Cannot read property 'get' of undefined
That indicates that state.resources is not defined. And sure enough, your state doesn't define a resources attribute.
The examples were written with the idea in mind of using redux-search to index many types of resources, eg:
state: {
resources: {
books: [...],
authors: [...],
// etc
}
}
The solution to the issue you've reported would be to either:
A: Add an intermediary resources object (if you think you might want to index other things in the future and you like that organization).
B: Replace state.resources.get(resourceName) with state[resourceName] or similar.

#ngrx/store Ignore first emitted value

store.select() emits previous store state.
Is it possible to subscribe to changes from "this point forward" without getting the previous store value?
If you are not interested in the first emitted value, you should be able to use the skip operator:
store.select(...).skip(1)...
skip operators need piping now, you can use skip like this:
store.pipe(select(...), skip(1));
In terms of the 'hacky' part, it is a standard practice in ngrx to set an initial state with properties set to null. and that value gets emitted initially. so the first value you get will be null in these cases.
Alternatively you could also consider skipwhile(https://www.learnrxjs.io/learn-rxjs/operators/filtering/skipwhile) and use it like this:
store.pipe(select(...), skipWhile(val => val === undefined));
where undefined is the initial value of the property you are interested in. Rather than setting the initial value of the property to undefined, you could use null as the initial value as well, and change the above skipwhile() accordingly.
Just sharing my thoughts (and solution) after reading #Niz's answer.
This is a perfect, practical example of how to utilize the difference between null and undefined. When you initialize your state with null, you're basically saying:
I don't care about differentiating the nullable future state from the
initial one. I don't care if the user is null because he has signed
out or because he just didn't sign in
However, in some cases this could be insufficient. Think about a case when you need an asynchronous call (implemented in effects) in order to know if you have an active user session. Based on the selection result, you should determine whether to show a login modal or redirect to a content page. With initial user state set to null, you'd pop up that modal and then immediately hide it when that asynchronous call returns a session value.
With initial state set to undefined you can make that differentiation, saying:
Initially, I know nothing about my state, then it's undefined. When I know it should be empty, then I'll set it to null.
Therefor, as a practical solution, I set everything on the app's initialState to undefined. In the example above, I need to know if the login modal should be displayed after the asynchronous call resolves. skipWhile(val => val === undefined) will do the job for sure, but repeating it over and over again feels a little tedious. Plus, it's not really descriptive to our use case. I created a rxjs-custom-operators.ts with a shortened implementation:
import { Observable } from "rxjs";
import { skipWhile } from "rxjs/operators";
export const skipInitial = () => {
return <T>(source: Observable <T>): Observable<T> => {
return source.pipe(skipWhile(value => value === undefined));
};
};
Usage:
navigateOnLoad(): void {
this.store.pipe(select(selectAuthUser), skipInitial()).subscribe((authUser: CognitoUser) => {
// Navigate to login if !authUser, else navigate to content...
});
}

Does Redux have a built-in way to undo actions?

I'm building an app where actions are performed as the user scrolls down. It would be nice if I could undo those actions as the user scrolls up again, basically turning scrolling into a way to browse through the time line of actions.
Is there a built-in way in Redux to do this? Or would I have to write middleware for this?
Is there a built-in way in Redux to do this? Or would I have to write middleware for this?
Middleware sounds like the wrong idea in this case because this is purely state management concern. Instead you can write a function that takes a reducer and returns a reducer, “enhancing” it with action history tracking along the way.
I outlined this approach in this answer, and it's similar to how redux-undo works, except that instead of storing the state, you can store actions. (Depends on the tradeoffs you want to make, and whether it's important to be able to “cancel” actions in a different order than they happened.)
I believe the idea is not so much "undo" as much as save a reference to the entire state tree each time an action passes through redux.
You would have a history stack made up of the application state at various times.
let history = [state1, state2, state3]
// some action happens
let history = [state1, state2, state3, state4]
// some action happens
let history = [state1, state2, state3, state4, state5]
// undo an action
let history = [state1, state2, state3, state4]
state = state4
To "undo" an action, you just replace the application state with one of the saved states.
This can be made efficient with data structures that support structural sharing, but in development we don't really need to consider resource constraints too much anyway.
I also wanted to create a simple undo functionality, but had already shipped an app with redux-storage that serializes and loads the state for every user. So to keep it backwards-compatible, I couldn't use any solution that wraps my state keys, like redux-undo does with past: [] and present:.
Looking for an alternative, Dan's tutorial inspired me to override combineReducers. Now I have one part of the state: history that saves up to 10 copies of the rest of the state and pops them on the UNDO action. Here's the code, this might work for your case too:
function shouldSaveUndo(action){
const blacklist = ['##INIT', 'REDUX_STORAGE_SAVE', 'REDUX_STORAGE_LOAD', 'UNDO'];
return !blacklist.includes(action.type);
}
function combineReducers(reducers){
return (state = {}, action) => {
if (action.type == "UNDO" && state.history.length > 0){
// Load previous state and pop the history
return {
...Object.keys(reducers).reduce((stateKeys, key) => {
stateKeys[key] = state.history[0][key];
return stateKeys;
}, {}),
history: state.history.slice(1)
}
} else {
// Save a new undo unless the action is blacklisted
const newHistory = shouldSaveUndo(action) ?
[{
...Object.keys(reducers).reduce((stateKeys, key) => {
stateKeys[key] = state[key];
return stateKeys;
}, {})
}] : undefined;
return {
// Calculate the next state
...Object.keys(reducers).reduce((stateKeys, key) => {
stateKeys[key] = reducers[key](state[key], action);
return stateKeys;
}, {}),
history: [
...(newHistory || []),
...(state.history || [])
].slice(0, 10)
};
}
};
}
export default combineReducers({
reducerOne,
reducerTwo,
reducerThree
});
For me, this works like a charm, it just doesn't look very pretty. I'd be happy for any feedback if this is a good / bad idea and why ;-)
There's no built-in way to do this.
but you can get inspired by how redux-dev-tools works (https://github.com/gaearon/redux-devtools). It basically have "time travel" functionality and it work by keep a track of all actions and reevaluating them each time. So you can navigate easily thorough all your changes.

Understanding how Router.go() works in Meteor

I'm just learning Meteor now from the great Discover Meteor book and I'm struggling to understand something about how Router.go() functions which I thought might be something that other beginners could use an answer to.
Context: The code below does what it's supposed to - it picks up the url and title values from the postSubmit form (code not included for the form) and uses that to create a new post. Then it uses Router.go() to take the user to the postPage template at a posts/:_id url, displaying the information for the newly created post. This code all works.
My question is: I would expect that when you call Router.go(), as well as passing in the 'postPage' template, what you would need to pass in as the second parameter is the post id element in the form {_id: post._id} (which also works, I've tried it) as that is what the route requires. So why am I passing in the post var (which includes the url and title) rather than the ID?
Here's my code:
//post_submit.js
Template.postSubmit.events({ 'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
post._id = Posts.insert(post);
//THE 'post' PARAMETER HERE INSTEAD OF '{_id: post._id}' IS WHAT I'M QUESTIONING
Router.go('postPage', post);
}
});
And the code for the router:
//Route for the postPage template
Router.route('/posts/:_id',
{name: 'postPage',
data: function(){ return Posts.findOne(this.params._id); }
});
Good question - I also found this confusing when I first saw it. Here's a sketch of what's going on:
The router parses /posts/:_id and figures out that it should be passed a context object which contains an _id field.
You call Router.go with a context object that contains an _id field.
The router takes your context object and copies the value of _id into this.params.
Because the router understands which fields are required (and ignores the rest), it doesn't actually matter if you pass in {_id: 'abc123'} or {_id: 'abc123', title: 'hello', author: 'bob'}. The fact that the latter works is simply a convenience so you don't have to extract the _id into a separate object.

Resources