locked
Data model as a json data source for react RRS feed

  • Question

  • User887623398 posted

    Hello,

    Is it possible to return the back-end model for react as a JSON file or a simple array for the data source?
    For example by a function with Axios and fetch?

    Is this correct:

    import React from 'react';
    
    
    import { FetchData } from './FetchData';
    
    const columns = ['CompanyName', 'City', 'State', 'Phone', 'Fax'];
    
    export default class DevGrid1 extends React.Component {
    
        constructor(props) {
            super(props);
            this.state = { myJson: [], loading: true };
        }
    
        componentDidMount() {
            this.jsonImageData()
        }
       
    
        static renderImageDataTable(myJson) {
            return (
                <DataGrid
                    dataSource={myJson}
                    defaultColumns={columns}
                    showBorders={true}
                />
                )
        }
    
        render() {
            let contents = this.state.loading
                ? <p><em>Loading...</em></p>
                : FetchData.renderImageDataTable(this.state.myJson);
    
            return (
                <div>
    
                    {contents}
    
                </div>
            );
        }
    
        async jsonImageData() {
            const response = await fetch('ImageData');
            const data = await response.json();
            this.setState({ myJson: data, loading: false });
        }
        
     
    }

    But this is not working!

    thanks,

    Thursday, January 21, 2021 5:12 PM

Answers

  • User475983607 posted

    I mean can I use fileIdList as a data source for components?

    I'm not sure how to answer your question.  fileIdList[] is an item in the component's state.  When state changes the React framework updates the associated DOM elements.  I guess you can consider fileIdList[] or any of the state items a source of data.

    Dude, read the docs and go through a few tutorials.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 22, 2021 8:04 PM

All replies

  • User475983607 posted

    Is it possible to return the back-end model for react as a JSON file or a simple array for the data source?
    For example by a function with Axios and fetch?

    SaeedP, what are you trying to do exactly?  Are you trying to call an Web API action from a React component? If so, this is covered in every beginning level React tutorial.  

    But this is not working!

    SaeedP, stop with the generic "not working!".   Explain the expected results and what is "not working!"  Share enough code the community can run to reproduce the unexpected behavior.

    Thursday, January 21, 2021 8:06 PM
  • User887623398 posted

    Yes, I want to use a component and it needs a JSON data source.

    For a day I'm looking forward to how to convert data to JSON.

    Also, I changed a bit the function:

    async jsonImageData() {
            const response = await fetch('ImageData');
            const data = await response.json();
            this.setState({ myJson: data, loading: false });
            
        }
    
    myJasonData = JSON.stringify(this.state.myJson);
    
    static renderImageDataTable(myJsonData) {
            return (
                <DataGrid
                    dataSource={myJsonData}
                    defaultColumns={columns}
                    showBorders={true}
                />
                )
        }

    I used a method, but still, nothing happens!

    Thursday, January 21, 2021 9:24 PM
  • User475983607 posted

    Again, fetching JSON and updating state is found in every beginning level React tutorial.   The code you've share above is similar to most of your posts where it looks like you mindlessly copied code from an internet blog without taking the time to understand what the code does.  You really need to set aside the time to learn the basics.  This does not happen in one day.

    At the same time you did not include the data model or the action that returns the data model.  The community cannot answer the question anyway...

    Below is a React component that uploads image files (your other post) and shows a list of files.  Keep in mind, the React code is not production ready and not well written but it should give you an idea of how to render a list and how to reference an image.

        public class Image
        {
            public int ImageId { get; set; }
            public string FileName { get; set; }
            public string Description { get; set; }
            public string Path { get; set; }
            public string ContentType { get; set; }
            public DateTime DateModified { get; set; }
           
        }
    
        public class ImageData
        {
            public string Description { get; set; }
            public IFormFile File { get; set; }
        }
    import React, { Component } from 'react';
    
    export class ImageUpload extends Component {
        static displayName = ImageUpload.name;
    
        constructor(props) {
            super(props);
            this.state = {
                selectedFile: null,
                description: null,
                uploadResult: null,
                fileIdList: []
            };
        }
    
        getList = () => {
            fetch('/api/images')
                .then(response => response.json())
                .then(data => this.setState({ fileIdList: data }));
        };
    
        componentDidMount() {
            this.getList();
        };
    
        onFileChange = event => {
            this.setState({ selectedFile: event.target.files[0] });
        };
    
        onDescriptionChange = event => {
            this.setState({ description: event.target.value })
        };
    
        onFileUpload = () => {
    
            const formData = new FormData();
    
            formData.append(
                "ImageData.File",
                this.state.selectedFile,
                this.state.selectedFile.name
            );
            formData.append("ImageData.Description", this.state.description);
    
            fetch('/api/images', {
                method: 'POST',
                body: formData
            }).then(resposne => resposne.json())
                .then(data => {
                    console.log(data);
                    this.setState({ uploadResult: "File " + data.fileName + " successfully uploaded." });
                    this.getList();
                });
        };  
    
        listItems = () => {
            const listItems = this.state.fileIdList.map((item) => 
                <div key={item.imageId.toString()}>
                    <img src={"/api/images/downloadimage/" + item.imageId}
                        alt={item.fileName}
                        className="img-thumbnail"
                        height="100" width="100" />
                </div>          
            );
            return (<div>{listItems}</div>);
        };
    
        render() {
    
            return (
                <div>
                    <h1>File Upload Demo</h1>
                    <div>{this.state.uploadResult}</div>
                    <div>
                        <input type="file" onChange={this.onFileChange} />
                        <input type="text" value={this.state.value} onChange={this.onDescriptionChange} />
                        <button onClick={this.onFileUpload}>
                            Upload!
                        </button>
                    </div>
                    {this.listItems()}
                </div>         
            );
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using ReactDemo.Data;
    using ReactDemo.Models;
    using ReactDemo.Models.ReactDemoViewModels;
    
    namespace ReactDemo.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ImagesController : ControllerBase
        {
            private readonly ReactDemoContext _context;
    
            public ImagesController(ReactDemoContext context)
            {
                _context = context;
            }
    
            // GET: api/Images
            [HttpGet]
            public async Task<ActionResult<IEnumerable<Image>>> GetImages()
            {
                return await _context.Images.ToListAsync();
            }
    
            // GET: api/Images/5
            [HttpGet("{id}")]
            public async Task<ActionResult<Image>> GetImage(int id)
            {
                var image = await _context.Images.FindAsync(id);
    
                if (image == null)
                {
                    return NotFound();
                }
    
                return image;
            }
    
            [HttpGet("DownloadImage/{id}")]
            public async Task<ActionResult<Image>> DownloadImage(int id)
            {
                var image = await _context.Images.FindAsync(id);
                System.IO.FileStream bytes = System.IO.File.OpenRead(image.Path);
                return File(bytes, image.ContentType);
            }
    
            // POST: api/Images
            // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
            [HttpPost]
            public async Task<ActionResult<Image>> PostImage([FromForm] ImageData imageData)
            {
                if (imageData.File.Length > 0)
                {
                    var filePath = System.IO.Path.GetTempFileName();
                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await imageData.File.CopyToAsync(stream);
                    }
    
                    Image file =  await _context.Images.FirstOrDefaultAsync(f => f.FileName == imageData.File.FileName);
                    if(file == null)
                    {
                        Image image = new Image()
                        {
                            ContentType = imageData.File.ContentType,
                            DateModified = DateTime.Now,
                            FileName = imageData.File.FileName,
                            Path = filePath,
                            Description = imageData.Description
                        };
                        _context.Images.Add(image);
                        await _context.SaveChangesAsync();
                        return CreatedAtAction(nameof(GetImage), new { id = image.ImageId }, image);
                    }
                    else
                    {
                        return BadRequest($"The path, {filePath}, already exists. Submit an HTTP PUT to update the image.");
                    }
                }
                return BadRequest($" {nameof(PostImage)} Error: The image file is {imageData.File.Length} bytes.");
            }
    
            private bool ImageExists(int id)
            {
                return _context.Images.Any(e => e.ImageId == id);
            }
        }
    }
    

    Thursday, January 21, 2021 11:10 PM
  • User887623398 posted

    Again thank you for your help. As always you helped me.

    About your words:

    Many of you have the chance to work in large programming companies and learn many things from the coworkers. But about me, that wasn't true and never work in a large company.

    I have some questions about your code:

    1. Couldn't we write image class and image data class? Why we create them in two separate classes?
    2. In this way, do we save images in the temp folder? where we save the images?
    3. in this way, do we return JSON value in fileIdList?

    thanks,

    Friday, January 22, 2021 5:45 AM
  • User475983607 posted

    Many of you have the chance to work in large programming companies and learn many things from the coworkers. But about me, that wasn't true and never work in a large company.

    You are right, many forum members are on development teams. We have code reviews and we provide feedback similar to these forums.  The difference is team member typically follow the advice and take the time to learn the concepts.  I don't get the same feeling when reading your  posts.

    Couldn't we write image class and image data class? Why we create them in two separate classes?

    The code examples uses a view model.  I explained this code sample in your other thread.  View model patterns are covered extensively in the Getting Started links I keep asking you to go through.  Very simply, the ImageData view model contains the only two user inputs, file and description.

    In this way, do we save images in the temp folder? where we save the images?

    I wrote the following in your other thread, The files are saved in a temp directory.  You'll need to figure out how to organize the files.  The file upload  code comes directly from the official file upload docs which also explains file upload security.  A link provided in your previous thread.

    Again, it is up to you to come up with design to organize the files that makes sense for your application.

    in this way, do we return JSON value in fileIdList?

    I'm not sure what you are asking.  The fileIdList[] contains the the JSON object below.  You can see the JSON response by opening the browser's dev tools and simply viewing the response.

    [
      {
        "imageId": 1,
        "fileName": "guitar_PNG3338.png",
        "description": "null",
        "path": "C:\\Users\\user\\AppData\\Local\\Temp\\tmpC64B.tmp",
        "contentType": "image/png",
        "dateModified": "2021-01-22T07:38:34.6387644-05:00"
      }
    ]

    Friday, January 22, 2021 12:49 PM
  • User887623398 posted

    I'm not sure what you are asking.  The fileIdList[] contains the the JSON object below.  You can see the JSON response by opening the browser's dev tools and simply viewing the response.

    I mean can I use fileIdList as a data source for components?

    Friday, January 22, 2021 6:33 PM
  • User475983607 posted

    I mean can I use fileIdList as a data source for components?

    I'm not sure how to answer your question.  fileIdList[] is an item in the component's state.  When state changes the React framework updates the associated DOM elements.  I guess you can consider fileIdList[] or any of the state items a source of data.

    Dude, read the docs and go through a few tutorials.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 22, 2021 8:04 PM