I've followed some fairly basic tutorials to set up a basic Web Api service and a React TS app to consume this, but when my react component calls the WebApi service, I can see the Web Api gets stepped into and returns the data - as it does if I enter the API url in the browser, it returns the correct items JSON, but in the javascript code for React, the HTTP response doesn't appear to contain any data when the promise comes back from fetch, just an empty 200 response.
Ie response.data is undefined.
This must be something very basic I'm doing wrong - as like I mentioned when you enter the API url in the browser, you see the correct JSON in the browser. So why cant my react code understand the response?
My Web Api
[EnableCors("*", "*", "*")]
public class ItemsController : ApiController
{
private readonly Item[] _items = {
new Item
{
...
},
new Item
{
...
},
new Item
{
...
},
};
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, _items);
}
public HttpResponseMessage Get(long id)
{
var item= _items.FirstOrDefault(t => t.ItemId == id);
if (item== null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not found");
}
return Request.CreateResponse(HttpStatusCode.OK, item);
}
}
My react component
import * as React from 'react';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';
import '../../App.css';
import IStoreState from '../../interfaces/IStoreState';
import Item from '../../model/item';
import { getItemsReceivedAction } from './actions';
interface IItemsProps {
items: Item[],
itemsUpdated: (items:Item[]) => void
}
class Trades extends React.Component<IItemsProps> {
constructor(props:IItemsProps) {
super(props);
}
public componentDidMount() {
fetch('http://localhost:58675/api/items', {
headers: {
Accept: 'application/json',
},
method: 'GET'
}).then((t:any) =>
{
const results = t;
this.props.itemsUpdated(results.data);
} );
}
public render() {
return (
<div>
{this.props.items} items displayed
</div>
);
}
}
const mapDispatchToProps = (dispatch:Dispatch) => {
return {
itemsUpdated: (items:Item[]) => dispatch(getItemsReceivedAction(items))
}
}
function mapStateToProps(state:IStoreState) {
return {
items: state.viewingItems
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Items);
Edit: javascript results object below
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:58675/api/items"
__proto__: Response
itemsare inresults.dataand notresults? I think this is your problem. Try changingthis.props.itemsUpdated(results.data);tothis.props.itemsUpdated(results);