I want to Get Shop Details For a logged in user in react component called Panel
If the shop exists for that user, it should show the details, otherwise should show a message.
Here is the Panel react component:
import React, {useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import CircularProgress from '@material-ui/core/CircularProgress';
import axios from "axios";
import config from 'config';
const url = `${config.apiUrl}/api/Shops`
export const Panel=()=> {
const [loading, setLoading] = useState(true);
const[shop,setShop]=useState(undefined);
const user=JSON.parse(localStorage.getItem('user'))
useEffect(()=>{
axios.get(url + `userId=${user.id}`).then((res)=>{
setShop(res.data);
} );
setTimeout(()=>{
setLoading(false);
},1000)
},[]);
console.log("shop",shop);
//
return (
<div>
{loading === true ? (<CircularProgress />): (
<div>
<h2> Dashboard</h2>
{shop[0]!=undefined ? <h3>{shop[0].storeName}</h3>:<h3>No Details Found</h3>}
</div>
)
}
</div>
);
}
Here is the Shop
model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApi.Models
{
public class Shop
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
[StringLength(150)]
public string StoreName { get; set; }
[DataType(DataType.MultilineText)]
public string Details { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public DateTime UpdatedOn { get; set; }
}
}
Here is controller - get shop by Id:
// GET: api/Shops/5
[HttpGet("{id}")]
public async Task<ActionResult<Shop>> GetShop(int id)
{
var shop = await _context.Shops.FindAsync(id);
if (shop == null)
{
return NotFound();
}
return shop;
}
Here is Get Shop By userId:
// GET: api/Shops/5
[HttpGet("{userId}")]
public async Task<ActionResult<Shop>> Panel(int userId)
{
var shop = await _context.Shops.FindAsync(userId);
if (shop == null)
{
return NotFound();
}
return shop;
}
The problem is that I want to Get the Shop By userId instead of id, because we have only userId
based on which we could get shop. We don't have shop id
.
Moreover, if there is problem in my axios call ,than also help to workaround.
Thanks in advance.
My app uses react+ node with front end and asp.net web api as backend.
If you want to get the shop data by userId, modify your code like below:
var shop = await _context.Shops.FirstOrDefaultAsync(a=>a.UserId==userId);