Skip to main content

Update from a component

Intro

Inside a component, when you register a ripple hook, it looks like a normal useState, except that it takes the name of the ripple. Use the ripple to get any values and use the updater to update the ripple.

The updater is used with or without parameters, depending on the action you want to take. By default, it will apply all current modifications that you made on the ripple object.

Example

import { createRipples } from  "@m-c2/ripple";

const lake = createRipples({
counter : { count: 0}
});

export const rippleHooks = lake[0];
export const rippleServices = lake[1];

In this example, we modify the counter object directly and then we call the updater without any parameters. Calling the updater without parameters will apply all modifications that you made on the ripple object.

Updater parameters

The updater can also be used with parameters to apply only some modifications.

FunctionParametervalueDescriptionTrigger a render
setCountervoidApply all pending changestrue
setCounterstringrestoreCancel the current local modificationfalse
setCounterstringresetReset the ripple to its initial statetrue
setCounterstring, TRipplereplace, ObjectReplace the current ripple state with a new one, does not impact the initial state in case of resettrue
// Apply all pending changes
// setCounter(void);
setCounter();

// Cancel the current local modification
// setCounter('restore');
setCounter('restore');

// Reset the ripple to its initial state
// setCounter('reset');
setCounter('reset');

// Replace the current ripple state with a new one,
// does not impact the initial state in case of reset
// setCounter('replace', typeof counter);
setCounter('replace', { count: 0 });

Parent / Child approach

The update can be done from any component as this Ripple is shared between all components that use it. So If you want to adopt a Parent / Children approach, you can do it easily.

const Parent = () => {
const [counter, setCounter] = useCounter();

return (
<MyComponent
increment={() => {
counter.count++;
setCounter();
}}

reset={() => {
setCounter("reset");
}}
/>
);
};

See it in action

Try it yourself here

Counter: 1