EzDevInfo.com

redux

Predictable state container for JavaScript apps Read Me | Redux redux is a predictable state container for javascript apps.

WordPress redux framework - Add custom fiedl to post type from child theme

I have a WordPress theme with a few post types, the theme runs on redux framework.

I want to add to a specific post type a custom field from the functions.php file in child theme without editing core files/installing plugins for it.

How could i do it? looking for something like:

if(is_post_type("some_post_type")&& is_admin_single_editor()){
     // Add custom field to edit screen
}

Thanks


Source: (StackOverflow)

How to tween model changes in react or where to resolve collision for fluent pure rendering

My State

I have a array of items in the following format:

[{ left: 0 }, { left: 10 }, { left: 20 }]

I can add an item { left: 30 } to this array:

[{ left: 0 }, { left: 10 }, { left: 20 }, { left: 30 }]

I can add a duplicate item { left: 20 } to this array:

[{ left: 0 }, { left: 10 }, { left: 20 }, { left: 20 }, { left: 30 }]

My View

I have to render these items on a plane, at position x, where x is their left property.

[{ left: 0 }, { left: 10 }, { left: 20 }] renders |item1 item2 item3|

[{ left: 0 }, { left: 10 }, { left: 20 }, { left: 30 }] renders |item1 item2 item3 item4 item5|

When there is a duplicate, I have to resolve this duplication by shifting elements left or right. So

[{ left: 0 }, { left: 10 }, { left: 20 }, { left: 20 }, { left: 30 }] renders |item1 item2 item3 item4 item5|

So they should not overlap.

I can add new items one by one, where new item can have any left property multiple of 10.

In case of an overlap, items should resolve the overlap by shifting right.

This could result in multiple items to be shifted to the right.

Example:

[{ left: 0 }, { left: 10 }, { left: 20 }, { left: 20 }, { left: 30 }, { left: 40 }]

resolving this requires shifting both items with left property 30 and 40. It becomes

[{ left: 0 }, { left: 10 }, { left: 20 }, { left: 30 }, { left: 40 }, { left: 50 }]

The shifting of items have to be animated/tweened. How can I enforce this requirement in React and flux architecture?

A. Resolve overlap within stores by tweaking left properties of the model, reflecting change in the view with tween. - How do I reflect a change to tween in React Components? - How do I resolve overlap?


Source: (StackOverflow)

Advertisements

How to install Redux flux in RoR? [closed]

I use React. I use gem 'react-rails' in RoR.

How to install the Redux project in Ruby on Rails application?

Tried https://github.com/rackt/react-redux Did not work.


Source: (StackOverflow)

Design Redux actions and reducers for a React reusable component

I'm developing a large application with Redux and React and I decided to make some reusable components like custom checkboxes and radio buttons.

As I want to store this information into the Redux store to be able to debug state of the application easily and the same component have the same functionality everywhere, it seems a good idea to create reducers and actions for each component.

However Redux reducers return a new state and save it in the store with the name of the reducer as a key and this forbids having more than one component of the same type in the same page using the same actions and reducers but keeping different states.

I think there are two solutions to this problem:

  • Create different actions and reducers for each component that I use, even thought the component and it's functionalities are the same. This solutions doesn't seem a good solution because there will be a lot of redundant code.

  • Create actions with sufficient parameters to be able to differentiate each one in the reducer and that way change only the part of the state that is specified.

I went forward with the second option.

Actions file for the CheckBox component:

import {createAction} from 'redux-actions';

/****** Actions ******/
export const CHANGE_CHECKBOX_STATE = "CHANGE_CHECKBOX_STATE";

/****** Action creators ******/
export const changeCheckboxState = createAction(CHANGE_CHECKBOX_STATE, (block, name, state) => {
  return {
    block,
    name,
    state: {
      checked: state,
    }
  };
});

Reducers file for the CheckBox component:

import {handleActions} from 'redux-actions';

import {CHANGE_CHECKBOX_STATE} from './CheckBox.actions';

export const checkBoxComponent = handleActions({
  CHANGE_CHECKBOX_STATE: (state, action) => ({
    [action.payload.block]: {
      [action.payload.name]: action.payload.state
    }
  })
}, {});

I use block to specify the page, name to specify the name of the specific component (e.g. gender) and state as and object with the new state.

But this solution has some problems too:

  • Can't specify initial state of each component because the keys of the state are dynamic.
  • Complicates to much the store structure with a lot of nested states.
  • Aggregates data by component and not by form which will complicate debugging and it's logically incorrect.

I don't have enough experience with Redux and React to think of a better solution to this problem. But it seems to me that I'm missing something important about React-Redux relationship and this raises some questions:

  • Is it a good idea to store state of this reusable components into the Redux store?

  • Am I wrong in binding together React components with Redux actions and reducers?


Source: (StackOverflow)

How to logically combine react-router and redux for client- and server-side rendering

I'd like my React based SPA to render on server side (who's not these days). Therefore I want to combine React with react-router, redux and some build layer like isomorphic starterkit.

There is hapi universal redux which joins all together, but I am struggling with how to organize my flow. My data is coming from multiple endpoints of a REST API. Different components have different data needs and should load data just in time on the client. On the server instead, all data for a specific route (set of components) has to be fetched, and the necessary components rendered to strings.

In my first approach I used redux's middleware to create async actions, which load the data, return a promise, and trigger a SOME_DATA_ARRIVED action when the promise resolves. Reducers then update my store, components re-render, all good. In principle, this works. But then I realized, that the flow becomes awkward, in the moment routing comes into play.

Some component that lists a number of data records has multiple links to filter the records. Every filtered data set should be available via it's own URL like /filter-by/:filter. So I use different <Link to={...}> components to change the URL on click and trigger the router. The router should update the store then according to the state represented by the current URL, which in turn causes a re-render of the relevant component.

That is not easy to achive. I tried componentWillUpdate first to trigger an action, which asynchronously loaded my data, populated the store and caused another re-render cycle for my component. But this does not work on the server, since only 3 lifecycle methods are supported.

So I am looking for the right way to organize this. User interactions with the app that change the apps state from the users perspective should update the URL. IMO this should make the router somehow load the necessary data, update the store, and start the reconciliation process.

So interaction -> URL change -> data fetching -> store update -> re-render.

This approach should work on the server also, since from the requested URL one should be able to determine the data to be loaded, generate initial state and pass that state into the store generation of redux. But I do not find a way to properly do that. So for me the following questions arise:

  1. Is my approach wrong because there is something I do not understand / know yet?
  2. Is it right to keep data loaded from REST API's in redux's store?
  3. Is'nt it a bit awkward to have components which keep state in the redux store and others managing their state by themselfs?
  4. Is the idea to have interaction -> URL change -> data fetching -> store update -> re-render simply wrong?

I am open for every kind of suggestion.


Source: (StackOverflow)

What is the best practice to create a flux isomorphic app?

I think that Isomorphic Application concept is really great. Suppose we use Flux as data-flow pattern.

How can we make stores local (for each request) and global (for those stores and data we want to share with all request, i.e. visit counter)?

How can we make data fetching for client and server when we want to have same state on sever side and on client side using rehydration?

Actually I'm learning Redux, but I can't find a correct way to solve all of these problems.

Also I'm looking for a good way to manage my API, that sould be callbale on client side (using REST API) and on server side (direct call).

Thank you in advice!


Source: (StackOverflow)

React router v0.13.3 or v1.0.0-beta3?

I want to build a basic app using react, flux (redux) and react-router. It will be a isomorphic (universal) app. I am confused about which react-router version should i use?

0.13.3 or 1.0.0-beta3.

Asking because 1.0 is cool and has better support for isomorphic apps and have simplified other things as well but it's still in beta.

Anybody knows when will 1.0 finalized?


Source: (StackOverflow)

Shared Data in Redux

In my React/Flux apps, I've been using Dan Abramov's "Combining Stateless Stores" pattern to share data that doesn't belong in state and is needed by multiple stores to perform business logic.

In a Redux app, where should non-state data reside and where should the logic go that analyzes this data?


Source: (StackOverflow)

Global State in Redux

Where does state become global in a Redux app?

For example, in the todo app in the docs, state is defined as a parameter of the selector function select without being imported or explicitly passed:

function select(state) {
  return {
    visibleTodos: selectTodos(state.todos, state.visibilityFilter),
    visibilityFilter: state.visibilityFilter
  };
}

My best guess is that it becomes global when we pass the root reducer to createStore in the root container, or perhaps it showed up with dispatch when we wrapped the <App> component with connect():

export default connect(select)(App);

Also, if state is global, why does it need to be defined as a parameter for select?


Source: (StackOverflow)

webpack dev server CORS issue

I am using webpack-dev-server v1.10.1 to boost up my Redux project and I have the options below:

contentBase: `http://${config.HOST}:${config.PORT}`,
quiet: false,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: configWebpack.output.publicPath,
headers: {"Access-Control-Allow-Origin": "*"},
stats: {colors: true}

In the JS, I am using request from superagent to generate a HTTP GET call

request
          .get(config.APIHost + apiUrl)
          .set('Accept', 'application/json')
          .withCredentials()
          .end(function (err, res) {
                if (!err && res.body) {
                    disptach(() => {
                        return {
                            type: actionType || GET_DATA,
                            payload: {
                                response: res.body
                            }
                        }
                    });
                }
          });

But I got the CORS error:

XMLHttpRequest cannot load http://localhost:8000/api/getContentByType?category=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5050' is therefore not allowed access

Any suggestion to resolve this? Thanks a lot


Source: (StackOverflow)

Webpack-dev-server, redux, isomorphic react router invariant error

When running my server through webpack dev server, I get this error:

Uncaught Error: Invariant Violation: Server-side <Router>s need location,
branch, params, and components props. Try using Router.run to get all the 
props you need

My client entry file looks like this:

// ... imports ... 
let initialState = window.__INITIAL_STATE__;

Object.keys(initialState)
      .forEach(key => {
        initialState[key] = fromJS(initialState[key]);
      });
const reducer = combineReducers(reducers);
const store   = createStore(reducer, initialState);
React.render(
  <Provider store={store}>
    {() =>
      <Router children={routes} history={history} />
    }
  </Provider>,
  document.getElementById('react-view')
);

Everything renders on the server-side correctly, the problem is when I have this router code on the client side. It seems like the router is trying to act like a server-size router even though it's being run on the client.

The versions I am using are:

├── react@0.13.3
├── react-hot-loader@1.3.0
├── react-redux@0.8.2
├── react-router@1.0.0-beta3
├── redux@1.0.1
└── webpack-dev-server@1.10.1

Source: (StackOverflow)

Updating nested data in redux store

What's the best/correct way to update a nested array of data in a store using redux?

My store looks like this:

{
    items:{
        1: {
            id: 1,
            key: "value",
            links: [
                {
                    id: 10001
                    data: "some more stuff"
                },
                ...
            ]
        },
        ...
    }
}

I have a pair of asynchronous actions that updates the complete items object but I have another pair of actions that I want to update a specific links array.

My reducer currently looks like this but I'm not sure if this is the correct approach:

  switch (action.type) {
    case RESOURCE_TYPE_LINK_ADD_SUCCESS:
      // TODO: check whether the following is acceptable or should we create a new one?
      state.items[action.resourceTypeId].isSourceOf.push(action.resourceTypeLink);
      return Object.assign({}, state, {
        items: state.items,
      });
  }

Source: (StackOverflow)

A Store of Actions for optimistic updates is a good approach in Redux/Flux?

I've been working with optimistic updates in a React+Flux application and saw two things:

  1. What happens if a user attempts to close the window when exists some uncompleted actions. For example in Facebook, a message appears in the wall even if wasn't really persisted (this is what optimistic updates does, a more responsive application for the user). But, if a user post in the wall and immediately close the application (on logout or window close), the post could fail and he would not be alerted.
  2. I don't like the idea of Stores managing his own entities (for example messages) and the situation of the action triggered for persiste a message (loading, succesfull, failed?). It mixes things.

So I work on this and create an ActionStore to manage the state of the actions triggered by the components. Here is the source code and here is a live demo.

It works more or less like this:

  1. The root of the components hierarchy (container in redux) fetch the nextId of a new action and pass it to his childs like props (this is ugly).
  2. A child component fires an action: it keeps the actionId for ask it to the store after and call the action creator.
  3. The action creator creates a new Action and returns a function to the middleware.
  4. The function returned from the Action creates a new Promise with the API call and dispatches an action of type XX_START.
  5. The ActionStore listen to the XX_START action and saves it.
  6. The child component receives the new state and find the action with the saved id and ask it the current situation: loading, successful or failed.

I've done this mainly for separate the state of the "entities" from the state of the actions, but allows retrigger actions with the same payload too (this could be useful when we receive 500 response status if the server is temporarly down or if the user loose signal).

Also, having an store of actions allows to easily ask if they are pending actions before the user logout or close the window.

Note: I'm working with a Single Application Page web app against a Rest API, I'm not think to use this on server-side rendering

It's a viable option create a ActionStore or I'm breaking some Redux/Flux foundations? This could end the posibility of use React Hot Reloading and Time traveling?

You should answer with no mercy, I've probably done a bunch of ugly things but I'm learning React/Redux.


Source: (StackOverflow)

How to fire periodic actions using setTimeout and dispatcher in redux

How/Where can I dispatch actions periodically? Using recursive setTimeout to make a countdown.

Taken from the example, something similar to this:

// Can also be async if you return a function
export function incrementAsync() {
  return dispatch => {
    (function _r() {
      setTimeout(() => {
        // Yay! Can invoke sync or async actions with `dispatch`
        dispatch(increment());
        _r();
      }, 1000);
    })();
  };
}

So is this a good idea, or there is a better approach to this problem, like using middlewares or creating actions from somewhere else?

I prefer a generic version of this, where I can control start/stop of the timer via the store.

I've setup a sample implementation please take a look at https://gist.github.com/eguneys/7023a114558b92fdd25e


Source: (StackOverflow)

How to setup Ember like computed properties in Immutablejs and Redux and Flux and React

I am used to computed properties in Ember Object Model. It's a convenient way to specify computed properties that depend on other properties.

Say fullName depends on firstName and lastName, I can setup computed properties as a function computeProperties and call computeProperties each time I make a change.

Example:

function computeFullName(state) {
  const fullName = state.get('firstName') + state.get('lastName');
  const nextState = state.set('fullName', fullName);
  return nextState;
}

function computeProperties(state) {
  const nextState = computeFullName(state);
  return nextState;
}

// store action handler
[handleActionX](state) {

  let nextState = state.set('firstName', 'John');
  nextState = state.set('lastName', 'Doe');

  nextState = computeProperties(nextState);

  return nextState;
}

Is there a way to automatically setup computed properties so that I don't have to call extra functions each time. In Redux or in ImmutableJS.


Source: (StackOverflow)