reactjssanitygroq

How to filter API data in sanity.io using react.js?


Hello I am new to the community and learning how things work here. Please try to understand through my broken English.

suppose there are 200 data in API, but I just wanted to pull any 4 random data to frontend. To be more clear the data are blog posts from sanity.io using groq ql in React.js. Here is the code which displays all the data from the API. I have tried slice function but did not worked.

const SideBarBlog = () => {
  const [postData, setPost] = useState(null);
 
  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type=="post"]{
        title,
        slug,
        mainImage{
          asset->{
            _id,
            url
          },
          alt,
          
        }
      }`
      )
      .then((data) => setPost(data))
      .then((data) => console.log(postData))

      .catch(console.error);
  }, []);

return (
    <>
      {postData &&
        postData.map((post, index) => (
       
            <div className="row sidebar-blog mb-4 p-3" key={index}>
              <div className="col-md-8">
                {/* sideblog title */}
                <p className="sidebolg-blogtitle mb-1">{post.title}</p>
              </div>
            </div>
         
        ))}
    </>
  );
};

export default SideBarBlog;

Solution

  • After you set ur state with the posts, you can access a random post in the array like this:

    const postData = [{ post: "some post obj" }, { post: "another post obj" },  ];
    
    const random = Math.floor(Math.random() * postsData.length); 
    postData[random] //this returns a  random post
    

    With this you can now access random posts and create a new array of length 4 or however you wish to do it