Put request get ID | Axios, React, Redux - javascript

I want to make a PUT request to my server, but in order to do so I need an identifier for the specific object I need to update. And that is my problem, I don't know how to get the components id so I can fulfill my PUT request. Here's the code at the moment:
import axios from 'axios'
import settings from '../../../../settings'
axios.defaults.baseURL = settings.hostname
export const updateSettings = function(id, item) {
return dispatch => {
axios
.put(`${settings.hostname}/locks/${id}`, item)
.then(res => res.data)
.catch(err => console.log(err))
}
}
When console.log item I can see all the new thing I've typed in my input fields (the things I want to change), but I'm getting this also:
And sometimes 404. So my question is how can I get the id so I can make this put request. Thank you.
This is where I call updateSettings:
import React, { Component } from 'react'
import { updateSettings } from './redux/actions/updateSettingsAction'
import DoorSettingsForm from './components/doorsSettingsForm'
import { connect } from 'react-redux'
class DoorSettingsContainer extends Component {
submit(values) {
this.props.updateSettings(values)
}
render() {
return (
<div>
<DoorSettingsForm
onSubmit={this.submit.bind(this)}
item={this.props.location.state.item}
/>
</div>
)
}
}
function mapStateToProps(state) {
return { data: state.data }
}
export default connect(mapStateToProps, { updateSettings })(
DoorSettingsContainer
)

You've missed the id on the updateSettings() function
look at this line: export const updateSettings = function(id, item) {};
and then the line where you call it:
submit(values) {
this.props.updateSettings(values)
}
your item is your id here, and the item is nowhere to be found, i think this is where you get most of your problems atleast for now from.

What you are currently doing is passing the event object received by the onSubmit handler to the updateSettings method.
Mind that in your event handler you have access to both state and props:
submit() {
// this comes from the redux binding
const { data } = this.props
// this is local state, not sure what else of interest is in there
const item = this.state.location.item
// Just a guess, inspect your data to see what's appropriate here.
this.props.updateSettings(data.id, item)
}
Inspect your data, you probably need to access data.id or item.id to get the proper id updateSettings needs.
Also pay attention that if you are dispatching async actions this way, then depending on what middleware you are using, you will probably have to call dispatch when the async data comes in (e.g. where you can access res.data).

Related

Customize the predefined request-type

I'm stuck in a problem. I'm using react-admin for the admin panel.
Now, when editing a contact the API is called with resource type GET_ONE.
I want to add the data to the reducer so that my component can use that data. Currently, the API is getting called and the fields are getting the value.
I just want to add the data to the reducer or want to call the API on the component componentDidMount method.
Can anyone help me with this?
You can use the dispatch method in your component like that...
Component
/** Import */
import { bindActionCreators } from "redux";
/** methods */
selectProduct = index => {
this.props.dispatch({ type: "selectedProduct", payload: index });
};
onDeleteProduct = index => {
this.props.onDeleteProduct(index);
};
/** actions */
const mapActionsToProps = dispatch => {
return {
dispatch,
...bindActionCreators({ onDeleteProduct: deleteProduct }, dispatch)
};
};

How to React re-render list view from database ondelete

I have 2 files here one is the parent component sending data from the database, the other is the rendered info with a delete button.
Here is my latest attempt to delete the data from the data base (works) and re-render the list (doesn’t re-render) current error is that email is not a valid variable.
import React, { Component } from 'react';
import EmailItem from './EmailItem'
class Admin extends Component {
  constructor(props) {
    super(props);
    this.state = {
    allEmails: []
  }
  this.hideEmail = this.hideEmail.bind(this, email)
}
  componentDidMount() {
    fetch("/api/emails/")
      .then(res => res.json())
      .then(parsedJSON => parsedJSON.map(emails => ({
        email: `${emails.email}`,
        id: `${emails.id}`
      }))).then(emails => this.setState({allEmails: emails}))
  }
  hideEmail = () => this.setState({allEmails:emails})
  render() {
    return (
      <div>
        <h2>Admin Page</h2>
        <div>
          {this.state.allEmails.map((email) => {
            return <EmailItem
              key={email.id}
              email={email.email}
              onDelete = {() => this.onDelete(this, email.email)}/>
          })}
        </div>
      </div>
    );
  }
}
export default Admin;
import axios from 'axios'
import React, { Component } from 'react';
const EmailItem = ({email, onDelete}) => (
  <div>
    <h3>{email}</h3>
    <button
      onClick={(e) => {
      e.preventDefault()
      axios.delete("/api/emails/delete/", {
        data: {email: email}
      })
      onDelete()
      }
    }
    >
      Remove
  </button>
  </div>
)
export default (EmailItem)
It looks like your Admin component doesn't know of the changes that happened on the backend. You fire off a delete, which works, but that component only gets the "allEmails" on mount. With the component already mounted, you aren't calling the fetch again to get the latest email list, so it never re-renders.
There are a few ways to handle this, but basically you'll want to fetch the new list after the axios delete completes successfully.
An option would be to create a new function in your Admin component that will fetch the email list. You can then call that in the componentDidMount function and then also pass it to the child EmailItem component, which it can call when the delete call has been successful.
You are passing an onDelete() function, to that component, but I don't see that defined in your code. If that's the intention of that function, make sure it's refetching the latest list of emails and setting state to force the refresh.

React and Axios fires twice (once undefined, once successfully)

Following the React AJAX example i have created a JSX file which purpose is to fetch and render a movie.
For all i know, i am doing everything right here.
When i console.log the data in my render function i get 2 results:
Undefined
Object (which is the one i need, so this one is perfect)
How can i filter out the Undefined row without doing some if/else logic in my render function?
Iterating over the result will, of course, result in an error the first time, which will crash my application.
What's the best way to handle this?
EDIT: Maybe the app gets rendered before the Axios call is done in which case i am forced to do an if/else statement?
Heres my JSX file:
import React from "react";
import axios from "axios";
export default class NetflixHero extends React.Component {
constructor() {
super();
this.state = {
movie: []
}
}
}
componentDidMount() {
const apiKey = 'xxxxxxxx';
let requestUrl = 'https://api.themoviedb.org/3/' + this.props.apiAction + '&api_key=' + apiKey;
axios.get(requestUrl).then(response => {
this.setState({movie: response.data.results})
});
}
render() {
//Fires twice. Returns Undefined and an Object
console.log(this.state.movie[0]);
return(
<div></div>
)
}
Check the state inside the render method. With this approach you can render a loading screen:
import React from "react";
import axios from "axios";
export default class NetflixHero extends React.Component {
constructor() {
super();
this.state = {
movie: []
}
}
}
componentDidMount() {
const apiKey = '87dfa1c669eea853da609d4968d294be';
let requestUrl = 'https://api.themoviedb.org/3/' + this.props.apiAction + '&api_key=' + apiKey;
axios.get(requestUrl).then(response => {
this.setState({movie: response.data.results})
});
}
render() {
//Loading...
if( this.state.movie[0] === undefined ) {
return <div>Loading...</div>
}
//Loaded successfully...
return(
<div> Movie loaded... [Do action here] </div>
)
}
Explanation
Every time the state changes, a re-render will be triggered. The first time, your Component is constructed with this.state.movie = []. After that, componentDidMount() is triggered, which changes your state. This is triggering the render method a second time.
Is your post crossdomain?
If your request is a CORS (Cross-origin resource sharing) request it will be preceded with a OPTIONS (pre-flight) request. Have a look at CORS and more specifically to the pre-flighted requests.
Basically the OPTIONS request is used to check if you are allowed to perform the GET/POST request from that domain and what headers can be used for that request. This is not axios specific.

How to update state using Redux?

I am using this starter kit https://github.com/davezuko/react-redux-starter-kit and am following some tutorials at the same time, but the style of this codebase is slightly more advanced/different than the tutorials I am watching. I am just a little lost with one thing.
HomeView.js - This is just a view that is used in the router, there are higher level components like Root elsewhere I don't think I need to share that, if I do let me know, but it's all in the github link provided above.
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { searchListing } from '../../redux/modules/search'
export class HomeView extends React.Component {
componentDidMount () {
console.log(this.props)
}
render () {
return (
<main onClick={this.props.searchListing}>
<NavBar search={this.props.search} />
<Hero/>
<FilterBar/>
<Listings/>
<Footer/>
</main>
)
}
}
I am using connect() and passing in mapStateToProps to tell the HomeView component about the state. I am also telling it about my searchListing function that is an action which returns a type and payload.
export const searchListing = (value) => {
console.log(value)
return {
type: SEARCH_LISTINGS,
payload: value
}
}
Obviously when I call the method inside the connect() I am passing in an empty object searchListing: () => searchListing({})
const mapStateToProps = (state) => {
return {
search: { city: state.search }
}
}
export default connect((mapStateToProps), { searchListing: () => searchListing({}) })(HomeView)
This is where I am stuck, I am trying to take the pattern from the repo, which they just pass 1, I think anytime that action is created the logic is just add 1 there is no new information passed from the component.
What I am trying to accomplish is input search into a form and from the component pass the users query into the action payload, then the reducer, then update the new state with the query. I hope that is the right idea.
So if in the example the value of 1 is hardcoded and passed into the connect() method, how can I make it so that I am updating value from the component dynamically? Is this even the right thinking?
You almost got it right. Just modify the connect function to pass the action you want to call directly:
const mapStateToProps = (state) => ({
search: { city: state.search }
});
export default connect((mapStateToProps), {
searchListing
})(HomeView);
Then you may use this action with this.props.searchListing(stringToSearch) where stringToSearch is a variable containing the input value.
Notice : You don't seem to currently retrieve the user query. You may need to retrieve it first and then pass it to the searchListing action.
If you need to call a function method, use dispatch.
import { searchListing } from '../../redux/modules/search';
const mapDispatchToProps = (dispatch) => ({
searchListing: () => {
dispatch(searchListing());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(HomeView);
Then, you have made the function a prop, use it with searchListing.

Accessing Redux state in an action creator?

Say I have the following:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
}
}
And in that action creator, I want to access the global store state (all reducers). Is it better to do this:
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
or this:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return (dispatch, getState) => {
const {items} = getState().otherReducer;
dispatch(anotherAction(items));
}
}
There are differing opinions on whether accessing state in action creators is a good idea:
Redux creator Dan Abramov feels that it should be limited: "The few use cases where I think it’s acceptable is for checking cached data before you make a request, or for checking whether you are authenticated (in other words, doing a conditional dispatch). I think that passing data such as state.something.items in an action creator is definitely an anti-pattern and is discouraged because it obscured the change history: if there is a bug and items are incorrect, it is hard to trace where those incorrect values come from because they are already part of the action, rather than directly computed by a reducer in response to an action. So do this with care."
Current Redux maintainer Mark Erikson says it's fine and even encouraged to use getState in thunks - that's why it exists. He discusses the pros and cons of accessing state in action creators in his blog post Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.
If you find that you need this, both approaches you suggested are fine. The first approach does not require any middleware:
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
However you can see that it relies on store being a singleton exported from some module. We don’t recommend that because it makes it much harder to add server rendering to your app because in most cases on the server you’ll want to have a separate store per request. So while technically this approach works, we don’t recommend exporting a store from a module.
This is why we recommend the second approach:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return (dispatch, getState) => {
const {items} = getState().otherReducer;
dispatch(anotherAction(items));
}
}
It would require you to use Redux Thunk middleware but it works fine both on the client and on the server. You can read more about Redux Thunk and why it’s necessary in this case here.
Ideally, your actions should not be “fat” and should contain as little information as possible, but you should feel free to do what works best for you in your own application. The Redux FAQ has information on splitting logic between action creators and reducers and times when it may be useful to use getState in an action creator.
When your scenario is simple you can use
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
But sometimes your action creator need to trigger multi actions
for example async request so you need
REQUEST_LOAD REQUEST_LOAD_SUCCESS REQUEST_LOAD_FAIL actions
export const [REQUEST_LOAD, REQUEST_LOAD_SUCCESS, REQUEST_LOAD_FAIL] = [`REQUEST_LOAD`
`REQUEST_LOAD_SUCCESS`
`REQUEST_LOAD_FAIL`
]
export function someAction() {
return (dispatch, getState) => {
const {
items
} = getState().otherReducer;
dispatch({
type: REQUEST_LOAD,
loading: true
});
$.ajax('url', {
success: (data) => {
dispatch({
type: REQUEST_LOAD_SUCCESS,
loading: false,
data: data
});
},
error: (error) => {
dispatch({
type: REQUEST_LOAD_FAIL,
loading: false,
error: error
});
}
})
}
}
Note: you need redux-thunk to return function in action creator
I agree with #Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:
import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';
class App extends React.Component {
handleClick(){
const data = this.props.someStateObject.data;
this.props.someDispatchFunction(data);
}
render(){
return (
<div>
<div onClick={ this.handleClick.bind(this)}>Click Me!</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return { someStateObject: state.someStateObject };
};
const mapDispatchToProps = (dispatch) => {
return {
someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
I would like to point out that it is not that bad to read from the store -- it might be just much more convenient to decide what should be done based on the store, than to pass everything to the component and then as a parameter of a function. I agree with Dan completely, that it is much better not to use store as a singletone, unless you are 100% sure that you will use only for client-side rendering (otherwise hard to trace bugs might appear).
I have created a library recently to deal with verbosity of redux, and I think it is a good idea to put everything in the middleware, so you have everyhing as a dependency injection.
So, your example will look like that:
import { createSyncTile } from 'redux-tiles';
const someTile = createSyncTile({
type: ['some', 'tile'],
fn: ({ params, selectors, getState }) => {
return {
data: params.data,
items: selectors.another.tile(getState())
};
},
});
However, as you can see, we don't really modify data here, so there is a good chance that we can just use this selector in other place to combine it somewhere else.
Presenting an alternative way of solving this. This may be better or worse than Dan's solution, depending on your application.
You can get the state from the reducers into the actions by splitting the action in 2 separate functions: first ask for the data, second act on the data. You can do that by using redux-loop.
First 'kindly ask for the data'
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
}
}
In the reducer, intercept the ask and provide the data to the second stage action by using redux-loop.
import { loop, Cmd } from 'redux-loop';
const initialState = { data: '' }
export default (state=initialState, action) => {
switch(action.type) {
case SOME_ACTION: {
return loop(state, Cmd.action(anotherAction(state.data))
}
}
}
With the data in hand, do whatever you initially wanted
export const ANOTHER_ACTION = 'ANOTHER_ACTION';
export function anotherAction(data) {
return {
type: ANOTHER_ACTION,
payload: data,
}
}
Hope this helps someone.
I know I'm late to the party here, but I came here for opinions on my own desire to use state in actions, and then formed my own, when I realized what I think is the correct behavior.
This is where a selector makes the most sense to me. Your component that issues this request should be told wether it's time to issue it through selection.
export const SOME_ACTION = 'SOME_ACTION';
export function someAction(items) {
return (dispatch) => {
dispatch(anotherAction(items));
}
}
It might feel like leaking abstractions, but your component clearly needs to send a message and the message payload should contain pertinent state. Unfortunately your question doesn't have a concrete example because we could work through a 'better model' of selectors and actions that way.
I would like to suggest yet another alternative that I find the cleanest, but it requires react-redux or something simular - also I'm using a few other fancy features along the way:
// actions.js
export const someAction = (items) => ({
type: 'SOME_ACTION',
payload: {items},
});
// Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction}) => (<div
onClick={boundSomeAction}
/>);
const mapState = ({otherReducer: {items}}) => ({
items,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => mappedDispatches.someAction(mappedState.items),
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
// (with other mapped state or dispatches) Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction, otherAction, otherMappedState}) => (<div
onClick={boundSomeAction}
onSomeOtherEvent={otherAction}
>
{JSON.stringify(otherMappedState)}
</div>);
const mapState = ({otherReducer: {items}, otherMappedState}) => ({
items,
otherMappedState,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
otherAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
const {items, ...remainingMappedState} = mappedState;
const {someAction, ...remainingMappedDispatch} = mappedDispatch;
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => someAction(items),
...remainingMappedState,
...remainingMappedDispatch,
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
If you want to reuse this you'll have to extract the specific mapState, mapDispatch and mergeProps into functions to reuse elsewhere, but this makes dependencies perfectly clear.
I wouldn't access state in the Action Creator. I would use mapStateToProps() and import the entire state object and import a combinedReducer file (or import * from './reducers';) in the component the Action Creator is eventually going to. Then use destructuring in the component to use whatever you need from the state prop. If the Action Creator is passing the state onto a Reducer for the given TYPE, you don't need to mention state because the reducer has access to everything that is currently set in state. Your example is not updating anything. I would only use the Action Creator to pass along state from its parameters.
In the reducer do something like:
const state = this.state;
const apple = this.state.apples;
If you need to perform an action on state for the TYPE you are referencing, please do it in the reducer.
Please correct me if I'm wrong!!!

Categories

Resources